Learn / Binary search trees

Validate BST

A tree is a BST exactly when its inorder is strictly increasing. Check it either with an inorder walk that compares each value with the previous one, or by passing down the range (low, high) that each node must fit in. The same inorder view repairs a BST with two swapped values and checks whether a preorder can belong to a BST.

How to recognise it

  • Is this tree (or this traversal) a valid BST?
  • Two nodes were swapped by mistake.
  • A tree's values must be rearranged into a BST of the same shape.

Two ways to check

valid(n, lo, hi):                 # every value must be strictly between lo and hi
    if n is null: return true
    if not lo < n.val < hi: return false
    return valid(n.left, lo, n.val) and valid(n.right, n.val, hi)

Or walk inorder and make sure each value is larger than the previous one.

The rule that makes a BST, and how it compares with a heap, is on the Structures page.

Using the inorder

ProblemIdea
recover two swapped nodesfind the drops in the inorder; swap the first big and the last small value
binary tree to BST, same shapewrite the sorted values back in inorder
can this preorder be a BST?a stack: after moving right past a value, nothing may be smaller than it
dead enda leaf whose allowed range has shrunk to one value

Common mistakes

  • Checking only left.val < node.val < right.val.
  • Using int limits that equal real values; use longs or null for "no limit".

Problems

0 of 5 solved

Check yourself

Is [5, 1, 4, null, null, 3, 6] a BST?

What range must a right child of 5, under a left child of 10, fit?

With two values swapped in a BST, how many drops can the inorder have?