-
Notifications
You must be signed in to change notification settings - Fork 1
/
is_tree_balanced.py
28 lines (19 loc) · 968 Bytes
/
is_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
# Write a program that takes as input the root of a binary tree and checks whether the tree is height-balanced
import collections
def is_balanced_binary_tree(tree: BinaryTreeNode) -> bool:
BalancedStatusWithHeight = collections.namedtuple(
'BalancedStatusWithHeight', ('balanced', 'height')
)
def check_balanced(tree):
if not tree:
return BalancedStatusWithHeight(True, -1) # the base case
left_result = check_balanced(tree.left)
if not left_result.balanced:
return BalancedStatusWithHeight(False, 0)
right_result = check_balanced(tree.right)
if not right_result.balanced:
return BalancedStatusWithHeight(False, 0)
is_balanced = abs(left_result.height - right_result.height) <= 1
height = max(left_result.height, right_result.height) + 1
return BalancedStatusWithHeight(is_balanced, height)
return check_balanced(tree).balanced