Validate Binary Search Tree
Master this topic with zero to advance depth.
Validate Binary Search Tree
Is valid BST?
Level I: Inorder to Array
Intuition
A Binary Search Tree has a unique property: its inorder traversal (Left, Root, Right) produces a strictly increasing sequence of values. We can perform an inorder traversal, store the results in an array, and then check if the array is sorted and contains no duplicates.
Thought Process
- Perform DFS (Inorder).
- Store every
node.valin a list. - Iterate through the list and check if
list[i] < list[i+1].
Detailed Dry Run
| Node | Left Subtree | Right Subtree | Array |
|---|---|---|---|
| 2 | [1] | [3] | [1, 2, 3] |
| Result | Valid BST! |
Level II: Iterative Inorder (Stack)
Intuition
Using a stack, we can simulate the recursion of an inorder traversal. We push all left children of the current node onto the stack, then pop one, check it, and move to its right child.
Logic
Keep a pointer prev to the previously visited node. At each step, if current.val <= prev.val, it's not a valid BST.
Detailed Dry Run
Stack: [2, 1]. Pop 1, prev=1. Pop 2, prev=2 (2>1 OK). Push 3, Pop 3, prev=3 (3>2 OK).
Level III: Optimal (Recursive Bounds)
Intuition
Thought Process
Instead of storing the whole tree in an array, we can validate each node as we visit it by passing down an allowable range (min, max). For any node, all values in its left subtree must be less than the node's value, and all values in its right subtree must be greater.
Pattern
Top-Down DFS: Pass constraints from parent to children.
Diagram
10 (range: -∞, +∞)
/ \
5 15
/ \ / \
L R L R
(5 range: -∞, 10) (15 range: 10, +∞)Detailed Dry Run
| Node | Range (Min, Max) | Valid? |
|---|---|---|
| 10 | (-∞, +∞) | YES |
| 5 | (-∞, 10) | YES |
| 15 | (10, +∞) | YES |
⚠️ Common Pitfalls & Tips
Be careful with Integer.MIN_VALUE. Use null or Long for the initial bounds to handle nodes that contain the minimum possible integer value.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.