Skip to content

Commit c35c99b

Browse files
shirinyamanibrycedrennan
authored andcommitted
feature(C04_P04): add alternative solution
closes #224
1 parent ec8d61f commit c35c99b

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

chapter_04/p04_check_balanced.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,28 @@ def is_balanced_v1(node):
6464
return find_max_depth(node) - find_min_depth(node) < 2
6565

6666

67+
# Alternative Recursive Approach
68+
def _find_height(root):
69+
if root is None:
70+
return 0
71+
left_height = _find_height(root.left)
72+
if left_height == -1:
73+
return -1
74+
75+
right_height = _find_height(root.right)
76+
if right_height == -1:
77+
return -1
78+
79+
if abs(left_height - right_height) > 1:
80+
return -1
81+
82+
return max(left_height, right_height) + 1
83+
84+
85+
def is_balanced_v3(root):
86+
return _find_height(root) > -1
87+
88+
6789
def _gen_balanced_1():
6890
root = BinaryNode(1)
6991
root.left = BinaryNode(2)
@@ -118,7 +140,7 @@ def _gen_unbalanced_2():
118140
(_gen_unbalanced_2, False),
119141
]
120142

121-
testable_functions = [is_balanced_v1, is_balanced_v2]
143+
testable_functions = [is_balanced_v1, is_balanced_v2, is_balanced_v3]
122144

123145

124146
def test_is_balanced():

0 commit comments

Comments
 (0)