-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathp4_4.py
More file actions
27 lines (20 loc) · 668 Bytes
/
p4_4.py
File metadata and controls
27 lines (20 loc) · 668 Bytes
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
from utils.graphs import BiNode, ltbt
from utils.treeviz import viz_tree
def check_balanced(root: BiNode):
return check_bal_rec(root) > 0
def check_bal_rec(node: BiNode):
if not node:
return 0
depth_right = check_bal_rec(node.right)
depth_left = check_bal_rec(node.left)
if depth_right < 0 or depth_left < 0:
return -1
elif abs(depth_right-depth_left) > 1:
return -1
else:
return max(depth_right, depth_left) + 1
if __name__ == "__main__":
extree = ltbt([0, 11, 12, 21, 222, 55, None, 31, 21, None, 42])
viz_tree(extree)
resp = check_balanced(extree)
print(f"Is tree balanced {resp}")