-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathcheck_tree_balanced.py
64 lines (54 loc) · 1.56 KB
/
check_tree_balanced.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
#!/usr/bin/python
# Date: 2020-10-22
#
# Description:
# Implement a function to check if a binary tree is balanced. A balanced tree
# is defined to be a tree such that the heights of the two subtrees of any node
# never differ by more than one.
#
# Approach:
# Take height of left subtree and right subtree for each node and if difference
# in heights is more than 1 for any node, tree is not balanced.
#
# Complexity:
# O(N) Time
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def check_tree_balanced_utils(root):
if root is None:
return 0
height_left = check_tree_balanced_utils(root.left)
height_right = check_tree_balanced_utils(root.right)
if abs(height_left - height_right) > 1:
return False
return 1 + max(height_left, height_right)
def check_tree_balanced(root):
check = check_tree_balanced_utils(root)
if check is False:
return False
return True
def main():
root = Node(1)
assert check_tree_balanced(root) == True
root = Node(1)
root.left = Node(2)
assert check_tree_balanced(root) == True
root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
assert check_tree_balanced(root) == False
root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
root.right = Node(4)
assert check_tree_balanced(root) == True
root = Node(1)
root.left = Node(2)
root.left.left = Node(3)
root.right = Node(4)
root.right.right = Node(5)
assert check_tree_balanced(root) == True
main()