Algorithms · Level 2 Trees

Binary Search Trees

Check that a binary search tree is still valid by passing the allowed range down the tree, where comparing a node with its children is not enough.

  • smaller on the left, larger on the right
  • a lookup drops a whole subtree each step
  • pass down the allowed range

In a binary search tree, everything left of a node is smaller and everything right is larger, so a lookup drops a whole subtree at each step (half the tree when it's balanced). Trap: comparing a node with its direct children misses a deep value on the wrong side; pass the allowed range down.

def contains(node, x):
    while node:
        if x == node.value:
            return True
        if x < node.value:
            node = node.left
        else:
            node = node.right
    return False

Write is_bst(root): True if, for every node, all values in its left subtree are smaller and all values in its right subtree are larger. An empty tree is valid. Example: is_bst(Tree(5, Tree(3), Tree(8))) → True.

solution.py
Test Suites Pending
Output