implements print tree method

This commit is contained in:
2013-07-15 16:31:07 +02:00
parent e731857f82
commit 25936d8413
2 changed files with 45 additions and 4 deletions

View File

@@ -82,8 +82,27 @@ class BinarySearchTree():
""" """
Prints a nice version of the binary search node Prints a nice version of the binary search node
""" """
#TODO max_iter = 1000000000 # max number of nodes
return self.root_node.__str__() ite = 0
ret = ""
node = self.root_node
top = False # dictates when to climb one level
while(ite < max_iter):
while (node.has_left_child()):
node = node.left_child
top = True
ret += str(node.value) + " "
if top: # we need to climb one level
node = node.parent
top = False
ret += str(node.value) + " "
if (not node.has_right_child()):
return ret.strip() # removes superflous spaces
else:
node = node.right_child
ite += 1
return None # problem
@staticmethod @staticmethod
def is_search_tree(a_tree_root): def is_search_tree(a_tree_root):

View File

@@ -186,7 +186,7 @@ class test_binary_search_tree(unittest.TestCase):
self.assertEqual(bst.root_node.right_child.value, 20) self.assertEqual(bst.root_node.right_child.value, 20)
self.assertFalse(BinarySearchTree.is_search_tree(bst.root_node)) self.assertFalse(BinarySearchTree.is_search_tree(bst.root_node))
def test_print(self): def test_print_node(self):
bst = BinarySearchTree() bst = BinarySearchTree()
self.assertEqual(bst.min(), None) self.assertEqual(bst.min(), None)
@@ -206,11 +206,33 @@ class test_binary_search_tree(unittest.TestCase):
# \ # \
# 16 # 16
self.assertEqual(bst.__str__(), "4 6 10") #self.assertEqual(bst.__str__(), "4 6 10")
self.assertEqual(bst.root_node.__str__(), "4 6 10")
self.assertEqual(bst.root_node.right_child.__str__(), "10 16") self.assertEqual(bst.root_node.right_child.__str__(), "10 16")
self.assertEqual(bst.root_node.right_child.right_child.__str__(), "16") self.assertEqual(bst.root_node.right_child.right_child.__str__(), "16")
def test_print_tree(self):
bst = BinarySearchTree()
self.assertEqual(bst.min(), None)
node_val1 = 6
bst.add(node_val1)
node_val2 = 4
bst.add(node_val2)
node_val3 = 10
bst.add(node_val3)
node_val4 = 16
bst.add(node_val4)
# 6
# / \
# 4 10
# \
# 16
self.assertEqual(bst.__str__(), "4 6 10 16")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()