Validate Binary Search Tree
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Validate Binary Search Tree
Is valid BST?
Approach 1
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].
⏱ O(N)💾 O(N) (to store the array)
Detailed Dry Run
| Node | Left Subtree | Right Subtree | Array |
|---|---|---|---|
| 2 | [1] | [3] | [1, 2, 3] |
| Result | Valid BST! |
Approach 2
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.⏱ O(N)💾 O(H)
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).
Approach 3
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, +∞)⏱ O(N) (visiting each node once)💾 O(H) (recursion depth equal to tree height)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.