-
Notifications
You must be signed in to change notification settings - Fork 51
/
height_balanced_btree.py
62 lines (48 loc) · 1.34 KB
/
height_balanced_btree.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
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self, data):
if not self.root:
self.root = Node(data)
else:
self._add(data, self.root)
def _add(self, data, node):
if data <= node.data:
if node.left:
self._add(data, node.left)
else:
node.left = Node(data)
else:
if node.right:
self._add(data, node.right)
else:
node.right = Node(data)
def isBalanced(self, node):
if not node:
return True
lh = self.get_height(node.left)
rh = self.get_height(node.right)
if abs(lh - rh) <= 1 and self.isBalanced(node.left) and self.isBalanced(node.right):
return True
return False
def get_height(self, node):
if not node:
return 0
else:
i = max(self.get_height(node.left), self.get_height(node.right)) + 1
return i
def main():
bst = BST()
nodes = [8, 3, 10, 1, 6, 4, 7, 13, 14]
for n in nodes:
bst.add(n)
print(bst.isBalanced(bst.root))
if __name__ == '__main__':
main()