-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathmin-height-BST.py
69 lines (58 loc) · 1.67 KB
/
min-height-BST.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# MIN HEIGHT BST
# O(NlogN) time and O(N) space
def minHeightBst(array):
return minHeightHelper(array, None, 0, len(array) - 1)
def minHeightHelper(array, nodeBST, start, end):
if start > end:
return
mid = (start + end) // 2
if not nodeBST:
nodeBST = BST(array[mid])
else:
nodeBST.insert(array[mid])
minHeightHelper(array, nodeBST, start, mid - 1)
minHeightHelper(array, nodeBST, mid + 1, end)
return nodeBST
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
# O(N) time and space
""" def minHeightBst(array):
return minHeightHelper(array, 0, len(array) - 1)
def minHeightHelper(array, start, end):
if start > end:
return None
mid = (start + end) // 2
newNode = BST(array[mid])
newNode.left = minHeightHelper(array, start, mid - 1)
newNode.right = minHeightHelper(array, mid + 1, end)
return newNode
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value) """