def test_preorder_traversal(self): """Test that a preorder traversal returns the nodes in the BST in the correct order. """ #Tree should look like this # 23 # 12 34 # 9 15 45 # 56 bst = BinarySearchTree() self.assertEqual(bst.size, 0) self.assertEqual(bst.get_height(), -1) nodes = bst.traverse(TreeTraversalOrder.PRE_ORDER) for node in nodes: self.assertIsNone(node) nodes = [23, 12, 34, 9, 15, 45, 56] #add nodes for node in nodes: bst.insert(node) self.assertEqual(bst.get_height(), 3) self.assertEqual(bst.size, 7) #order should be 23, 12 9, 15, 34, 45, 56 i = 0 preorder = [23, 12, 9, 15, 34, 45, 56] for node in bst.traverse(TreeTraversalOrder.PRE_ORDER): self.assertEqual(preorder[i], node.data) i += 1
def test_level_order_traversal(self): """Test that a levelorder traversal returns the nodes in the BST in the correct order. """ #Tree should look like this # 23 # 12 34 # 9 15 45 # 56 bst = BinarySearchTree() self.assertEqual(bst.size, 0) self.assertEqual(bst.get_height(), -1) nodes = bst.traverse(TreeTraversalOrder.IN_ORDER) for node in nodes: self.assertIsNone(node) nodes = [23, 12, 34, 9, 15, 45, 56] #add nodes for node in nodes: bst.insert(node) self.assertEqual(bst.get_height(), 3) self.assertEqual(bst.size, 7) #this is the expected order i = 0 level_order = [23, 12, 34, 9, 15, 45, 56] for node in bst.traverse(TreeTraversalOrder.LEVEL_ORDER): self.assertEqual(level_order[i], node.data) i += 1
def test_invalid_traversal(self): """Test to ensure that the traverse method raises an error if an invalid traversal order is passed in as an arguement. """ #Tree should look like this # 23 # 12 34 # 9 15 45 # 56 bst = BinarySearchTree() self.assertEqual(bst.size, 0) self.assertEqual(bst.get_height(), -1) nodes = [23, 12, 34, 9, 15, 45, 56] #add nodes for node in nodes: bst.insert(node) self.assertEqual(bst.size, 7) nodes = bst.traverse(5) for node in nodes: self.assertIsNone(node)