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: Implement a binary search tree with an insert method.

Constraints

  • Can we assume we are working with valid integers?
    • Yes
  • Can we assume all left descendents <= n < all right descendents?
    • Yes
  • For simplicity, can we use just a Node class without a wrapper Tree class?
    • Yes
  • Do we have to keep track of the parent nodes?
    • This is optional

Test Cases

Insert

Insert will be tested through the following traversal:

In-Order Traversal (Provided)

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

Algorithm

Insert

  • If the data is <= the current node's data
    • If the current node's left child is None, set it to Node(data)
    • Else, recursively call insert on the left child
  • Else
    • If the current node's right child is None, set it to Node(data)
    • Else, recursively call insert on the right child

Complexity:

  • Time: O(log n)
  • Space: O(1)

Code


In [1]:
%%writefile bst.py
class Node(object):

    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.parent = None

    def __str__(self):
        return str(self.data)


def insert(root, data):
    if data <= root.data:
        if root.left is None:
            root.left = Node(data)
            root.left.parent = root
            return root.left
        else:
            return insert(root.left, data)
    else:
        if root.right is None:
            root.right = Node(data)
            root.right.parent = root
            return root.right
        else:
            return insert(root.right, data)


Overwriting bst.py

In [2]:
%run bst.py

Unit Test


In [3]:
%run dfs.py

In [4]:
%run ../utils/results.py

In [5]:
%%writefile test_bst.py
from nose.tools import assert_equal


class TestTree(object):

    def __init__(self):
        self.results = Results()

    def test_tree(self):
        node = Node(5)
        insert(node, 2)
        insert(node, 8)
        insert(node, 1)
        insert(node, 3)
        in_order_traversal(node, self.results.add_result)
        assert_equal(str(self.results), '[1, 2, 3, 5, 8]')
        self.results.clear_results()

        node = Node(1)
        insert(node, 2)
        insert(node, 3)
        insert(node, 4)
        insert(node, 5)
        in_order_traversal(node, self.results.add_result)
        assert_equal(str(self.results), '[1, 2, 3, 4, 5]')

        print('Success: test_tree')


def main():
    test = TestTree()
    test.test_tree()


if __name__ == '__main__':
    main()


Overwriting test_bst.py

In [6]:
%run -i test_bst.py


Success: test_tree