Example #1
0
    def test_add(self):
        bst = BinarySearchTree()
        bst.add(7)
        self.assertEqual(bst.root.value, 7)
        self.assertIsNone(bst.root.left)
        self.assertIsNone(bst.root.right)

        bst.add(4)
        self.assertIsNotNone(bst.root.left)
        self.assertEqual(bst.root.left.value, 4)

        bst.add(10)
        self.assertIsNotNone(bst.root.right)
        self.assertEqual(bst.root.right.value, 10)

        bst.add(6)
        self.assertEqual(bst.root.left.right.value, 6)
Example #2
0
""""
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.
"""


from implementations.tree import BinarySearchTree


def in_order_successor(root, el):
    succ = None
    while root:
        if root.value > el:
            succ = root
            root = root.left
        else:
            root = root.right

    return succ


if __name__ == "__main__":
    bst = BinarySearchTree.from_array([1, 4, 5, 7, 8, 9, 10])
    print in_order_successor(bst.root, 5)
Example #3
0

def traverse(root, first, second, prev):
    if root is not None:
        first, second, prev = traverse(root.left, first, second, prev)
        if prev and root.value < prev.value:
            if first is None:
                first = prev
            second = root
        prev = root
        first, second, prev = traverse(root.right, first, second, prev)
    return first, second, prev


if __name__ == "__main__":
    bst = BinarySearchTree.from_array([1, 4, 5, 7, 8, 9, 10])
    print bst
    bst.root.left.value, bst.root.right.left.value = bst.root.right.left.value, bst.root.left.value
    print bst
    fix_bst(bst)
    print bst

    print
    bst = BinarySearchTree()
    bst.add(0)
    bst.root.left = BinaryTreeNode(1)
    print bst
    fix_bst(bst)
    print bst
    print