Learn / Binary search trees

Largest BST in a binary tree

To find the largest subtree that is a BST, let each node report, from a post-order pass: whether its subtree is a BST, its size, and its smallest and largest values. A node's subtree is a BST when both children's are and the left maximum is below the node and the right minimum above it.

How to recognise it

  • The biggest part of a tree with some property, checked bottom up.
  • Whether a subtree is a BST, for every subtree.
  • O(n) instead of checking each subtree from scratch.

Four facts per subtree

scan(n): if null: (size 0, min +inf, max -inf)
         (ls, lmin, lmax) = scan(left); (rs, rmin, rmax) = scan(right)
         if a side is not a BST or lmax >= n.val or rmin <= n.val: not a BST
         size = ls + rs + 1; best = max(best, size)
         return (size, min(lmin, n.val), max(rmax, n.val))

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

The empty subtree reports min +∞ and max -∞, so any parent value fits next to it.

Common mistakes

  • Returning the largest BST size but then using it as if the subtree itself were a BST.
  • Forgetting that both children must be BSTs, not just the near values.

Problems

0 of 1 solved

Check yourself

What does each node need from its children?

A leaf is?

Why is checking every subtree separately slow?