forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BST_Construction_Iterative.py
81 lines (73 loc) · 3.09 KB
/
BST_Construction_Iterative.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
70
71
72
73
74
75
76
77
78
# https://www.algoexpert.io/questions/BST%20Construction
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Average: O(log(n)) time | O(1) space
# Worst: O(n) time | O(1) space
def insert(self, value):
currentNode = self
while True:
if value < currentNode.value:
if currentNode.left is None:
currentNode.left = BST(value)
break
else:
currentNode = currentNode.left
else:
if currentNode.right is None:
currentNode.right = BST(value)
break
else:
currentNode = currentNode.right
return self
# Average: O(log(n)) time | O(1) space
# Worst: O(n) time | O(1) space
def contains(self, value):
currentNode = self
while currentNode is not None:
if value < currentNode.value:
currentNode = currentNode.left
elif value > currentNode.value:
currentNode = currentNode.right
else:
return True
return False
# Average: O(log(n)) time | O(1) space
# Worst: O(n) time | O(1) space
def remove(self, value, parentNode=None):
currentNode = self
while currentNode is not None:
if value < currentNode.value:
parentNode = currentNode
currentNode = currentNode.left
elif value > currentNode.value:
paretNode = currentNode
currentNode = currentNode.right
else:
if currentNode.left is not None and currentNode.right is not None:
currentNode.value = currentNode.right.getMinValue() # currentNode.value = smallest value of the right subtree
currentNode.right.remove(currentNode.value, currentNode)
elif parentNode is None:
if currentNode.left is not None:
currentNode.value = currentNode.left.value
currentNode.right = currentNode.left.right
currentNode.left = currentNode.left.left
elif currentNode.right is not None:
currentNode.value = currentNode.right.value
currentNode.left = currentNode.right.left
currentNode.right = currentNode.right.right
else:
currentNode.value = None
elif parentNode.left == currentNode:
parentNode.left = currentNode.left if currentNode.left is not None else currentNode.right
elif parentNode.right == currentNode:
parentNode.right = currentNode.left if currentNode.left is not None else currentNode.right
break
return self
def getMinValue(self):
currentNode = self
while currentNode.left is not None:
currentNode = currentNode.left
return currentNode.value