Exemplo n.º 1
0
    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
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
    def test_invalid_traversal(self):
        """Test to ensure that the traverse method
        returns an empty generator.
        """
        #Tree should look like this
        #        23
        #     12     34
        #   9   15      45
        #                 56

        bst = BinarySearchTree()
        self.assertEqual(bst.size, 0)

        #add level 1
        bst.insert(23)

        #add level 2
        bst.insert(12)
        bst.insert(34)

        #add level 3
        bst.insert(9)
        bst.insert(15)
        bst.insert(45)

        #add level 4
        bst.insert(56)

        self.assertEqual(bst.size, 7)

        nodes = bst.traverse(5)
        for node in nodes:
            self.assertIsNone(node)