This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
The algorithm will be similar to where we get the height of a tree as seen in here.
However, we could check whether the tree is balanced while also checking for the heights.
root.left
, if -1, return -1root.right
, if -1, return -1Complexity:
In [1]:
%run ../bst/bst.py
In [2]:
def check_balance(root):
if check_height(root) == -1:
return False
else:
return True
def check_height(root):
if root is None:
return 0
left_height = check_height(root.left)
if left_height == -1:
return -1
right_height = check_height(root.right)
if right_height == -1:
return -1
diff_height = left_height - right_height
if abs(diff_height) > 1:
return -1
else:
return 1 + max(left_height, right_height)
In [3]:
%%writefile test_check_balance.py
from nose.tools import assert_equal
class TestCheckBalance(object):
def test_check_balance(self):
node = Node(5)
insert(node, 3)
insert(node, 8)
insert(node, 1)
insert(node, 4)
assert_equal(check_balance(node), True)
node = Node(5)
insert(node, 3)
insert(node, 8)
insert(node, 9)
insert(node, 10)
assert_equal(check_balance(node), False)
print('Success: test_check_balance')
def main():
test = TestCheckBalance()
test.test_check_balance()
if __name__ == '__main__':
main()
In [4]:
%run -i test_check_balance.py