Validate Binary Search Tree
Recursive range narrowing (low, high)
Comparing a node only to its immediate children is the classic trap: it misses violations from further up the tree. Instead carry an open interval (low, high) downward, starting at (-infinity, infinity). A node must strictly fit the interval its ancestors handed down; its left child inherits the same low but a tightened high of the node's own value, and its right child inherits the same high but a tightened low. The moment a node fails its interval, the whole check returns false — no need to look further.
Details
Animated on: root = [5, 1, 4, null, null, 3, 6] — is this a valid BST? Expected answer: false (4 is less than root 5 but sits in 5's right subtree).
Problem:Validate Binary Search TreeMedium
Pattern:Binary Search Tree Problems
Recursive range narrowing (low, high)
step 1 / 8
Call stack
Enter 5. Its allowed range is (-inf, inf) and 5 fits: continue into its subtrees.
1FUNCTION validate(node, low, high):2 IF node = null: RETURN true3 IF NOT (low < node.val AND node.val < high): RETURN false4 leftOk <- validate(node.left, low, node.val)5 rightOk <- validate(node.right, node.val, high)6 RETURN leftOk AND rightOk7answer <- validate(root, -infinity, infinity)
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- Enter 5. Its allowed range is (-inf, inf) and 5 fits: continue into its subtrees.
- Enter 1. Its allowed range is (-inf, 5) and 1 fits: continue into its subtrees.
- Back at 1: its left subtree is valid. Now check its right subtree with a tightened lower bound of 1 (still capped at 5).
- 1's frame returns true (left true AND right true) and pops off the stack.
- Back at 5: its left subtree is valid. Now check its right subtree with a tightened lower bound of 5 (still capped at inf).
- Enter 4. Its allowed range is (5, inf) and 4 does NOT fit — an ancestor already forced a tighter bound. This node breaks the BST property.
- validate(4, ...) returns false immediately. Its own subtrees are never visited — one violation is enough to fail the whole tree.
- 5's frame returns false (left true AND right false) and pops off the stack.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.