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
| Problem | Idea |
|---|---|
| recover two swapped nodes | find the drops in the inorder; swap the first big and the last small value |
| binary tree to BST, same shape | write 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 end | a 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
- Validate Binary Search Treemediumguide ready
- Recover Binary Search Treemediumguide ready
- Convert Binary tree into BSTmediumguide ready
- Check preorder is valid or notmediumguide ready
- Check whether BST contains Dead endmediumguide ready