Skip to content

Commit

Permalink
trasverse tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt committed Jul 11, 2018
1 parent e86ea5e commit 5536970
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions python/app/binary_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ def __init__(self, val):
self.right = None
self.val = val

def __str__(self):
''' Preorder traversal
'''
s = '{}{}'.format(str(self.val), ' ')
if self.left is not None:
s += str(self.left)

if self.right is not None:
s += str(self.right)

return s

def insert(self, node):
if node.val < self.val:
if self.left is None:
Expand Down
13 changes: 13 additions & 0 deletions python/tests/test_binary_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,16 @@ def test_insert_nodes():

assert tree.left.val == 1
assert tree.right.val == 3


def test_preorder_traversal(capfd):
tree = BNode(10)
tree.insert(BNode(2))
tree.insert(BNode(12))
tree.insert(BNode(1))
tree.insert(BNode(11))
tree.insert(BNode(4))

print tree
out, err = capfd.readouterr()
assert out == '10 2 1 4 12 11 \n'

0 comments on commit 5536970

Please sign in to comment.