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).

Solution Notebook

Problem: Check if a binary tree is balanced.

Constraints

  • Is a balanced tree one where the heights of two sub trees of any node doesn't differ by more than 1?
    • Yes
  • Can we assume we already have a Node class with an insert method?
    • Yes

Test Cases

  • 5, 3, 8, 1, 4 -> Yes
  • 5, 3, 8, 9, 10 -> No

Algorithm

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.

  • Base case: If the root is None, return 0
  • Check the height of root.left, if -1, return -1
  • Check the height of root.right, if -1, return -1
  • If the height differences is greater than 1, return -1
  • Otherwise, return 1 + max(left height, right height)

Complexity:

  • Time: O(n)
  • Space: O(h), where h is the height of the tree

Code


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)

Unit Test


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()


Overwriting test_check_balance.py

In [4]:
%run -i test_check_balance.py


Success: test_check_balance