← Back to DSA
#98
Validate Binary Search Tree
Validate Binary Search Tree solution for LeetCode 98, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Validate Binary Search Tree
Why it belongs on this sheet
This problem is important because the tempting local check is wrong. Interviewers like it for that reason.
Pattern
Allowed value range
Approach
Carry a lower and upper bound down the recursion. Every node must stay strictly between those bounds.
Java solution
class Solution {
public boolean isValidBST(TreeNode root) {
return validate(root, null, null);
}
private boolean validate(TreeNode node, Long lower, Long upper) {
if (node == null) {
return true;
}
if ((lower != null && node.val <= lower) || (upper != null && node.val >= upper)) {
return false;
}
return validate(node.left, lower, (long) node.val)
&& validate(node.right, (long) node.val, upper);
}
}
Complexity
- Time:
O(n) - Space:
O(h)
Interview note
The whole point is that validity depends on ancestors, not just the direct parent.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)