AlgoFrames

Validating a BST and the in-order property

A tree is a BST only if every node fits the range allowed by all its ancestors. Watch the allowed range shrink down each path.

Before you start: BST delete; successor and predecessor.

The idea

Each child here sits on the correct side of its parent. Yet this tree is not a BST.

9 is in the left subtree of 8, so it must be smaller than 8. A check of each parent and child alone misses that.

Intuition

Here is a valid tree, with 6 where 9 was. Each node gets a range: going left lowers the upper bound, going right raises the lower.

A node inherits its range from its parent and then cuts it at the parent key. So every ancestor on the path leaves its mark.

A second test: read the keys in order (left, node, right). A tree is a BST exactly when they come out increasing.

Complexity

Each node is checked once, so the time is O(n). The recursion is as deep as the tree, so the space is O(h).

A valid tree must be checked completely, because any node could break the rule. A chain makes h equal to n.

Pitfalls

Comparing each node only with its parent passes this tree. The bound from 8 has to travel down the path.

Use strict bounds. A key equal to an ancestor breaks a BST with distinct keys.

Avoid fake bounds such as the smallest int. A real key can equal them. Use infinity or null to mean no bound.

Variations

In-order visits keys in increasing order. So the 3rd visit is the 3rd smallest key, here 6.

If 3 and 10 were swapped, in-order reads 1, 10, 6, 8, 3, 14 with drops after 10 and after 8. Swap those two keys back.

Code

Pseudocode

isBST(root)
  return check(root, −∞, +∞)
check(node, lo, hi)
  if node = null: return true
  if not (lo < node.val < hi): return false
  if not check(node.left, lo, node.val): return false
  return check(node.right, node.val, hi)

Python

def is_valid_bst(root):
    def check(node, lo, hi):
        if node is None:
            return True
        if not (lo < node.val < hi):
            return False
        if not check(node.left, lo, node.val):
            return False
        return check(node.right, node.val, hi)
    return check(root, float("-inf"), float("inf"))

JavaScript

function isValidBST(root) {
  function check(node, lo, hi) {
    if (node === null) return true;
    if (!(lo < node.val && node.val < hi)) return false;
    if (!check(node.left, lo, node.val)) return false;
    return check(node.right, node.val, hi);
  }
  return check(root, -Infinity, Infinity);
}

Practice problems (7)

Which tree fools a parent check? Warm-up

A careless check only compares each node with its two children. Pick the tree that passes this check but is not a BST.

The range of a deep node Warm-up

Node 4 must hold a key strictly between two bounds. Give the lower and the upper bound, separated by a comma.

Find the violating node Standard

One key in this tree breaks the BST rule. Follow the range check and answer each question before the step plays.

Validate a BST Standard

Given the root of a binary tree, return true if it is a valid binary search tree. Every key in the left subtree of a node must be smaller than the node key, and every key in the right subtree must be bigger. Equal keys are not allowed. An empty tree is valid.

K-th smallest Standard

Given the root of a BST and a number k, return the k-th smallest key in the tree (counting from 1).

Spot the bug: forgotten lower bound Standard

This check accepts some trees that are not BSTs. Click the line with the bug, then fix it.

Recover a swapped BST Challenge

The keys of two nodes of a BST were swapped by mistake. Swap them back and return the root. Do not change the shape of the tree. If the tree is already valid, return it unchanged.

Related topics

Next on the path: Why balance matters