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).
Complexity:
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)
In [2]:
%run bst.py
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()
In [6]:
%run -i test_bst.py