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

Challenge Notebook

Problem: Determine the height of a tree.

Constraints

  • Is this a binary tree?
    • Yes
  • Can we assume we already have a Node class with an insert method?
    • Yes

Test Cases

  • 5 -> 1
  • 5, 2, 8, 1, 3 -> 3

Algorithm

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [ ]:
%run ../bst/bst.py
%load ../bst/bst.py

In [ ]:
def height(node):
    # TODO: Implement me
    pass

Unit Test

The following unit test is expected to fail until you solve the challenge.


In [ ]:
# %load test_height.py
from nose.tools import assert_equal


class TestHeight(object):

    def test_height(self):
        root = Node(5)
        assert_equal(height(root), 1)
        insert(root, 2)
        insert(root, 8)
        insert(root, 1)
        insert(root, 3)
        assert_equal(height(root), 3)

        print('Success: test_height')


def main():
    test = TestHeight()
    test.test_height()


if __name__ == '__main__':
    main()

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.