98. Validate Binary Search Tree
Asked at 19Bloomberg64Microsoft55Amazon55Meta47Google36Apple22Lyft51Wix87Millennium76Asana61Yahoo61Expedia54Citadel47Oracle45Salesforce35IBM35Infosys30Yandex28LinkedIn20
Problem
Decide whether a binary tree is a valid binary search tree: for every node, all values in its left subtree are strictly smaller and all values in its right subtree strictly larger.
Example: [2,1,3] → true; [5,1,4,null,null,3,6] → false (3 sits in 5's right subtree)
Constraints: values span the full 32-bit range.
Each node must lie strictly within (lo, hi) inherited from ancestors — checking only direct children is the classic bug.
5 (−∞, ∞)
1 6 1:(−∞,5) 6:(5,∞)
3 7 3:(5,6) ✗ 3 < 5
Complexity: O(n).
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def ok(node, lo, hi):
if not node:
return True
if not lo < node.val < hi:
return False
return ok(node.left, lo, node.val) and ok(node.right, node.val, hi)
return ok(root, float("-inf"), float("inf"))
assert Solution().isValidBST(make_tree([2, 1, 3])) is True
assert Solution().isValidBST(make_tree([5, 1, 6, None, None, 3, 7])) is False
class Solution {
public boolean isValidBST(TreeNode root) { return ok(root, Long.MIN_VALUE, Long.MAX_VALUE); }
private boolean ok(TreeNode n, long lo, long hi) {
if (n == null) return true;
if (n.val <= lo || n.val >= hi) return false;
return ok(n.left, lo, n.val) && ok(n.right, n.val, hi);
}
}
func isValidBST(root *TreeNode) bool {
var ok func(node *TreeNode, lo, hi int) bool // every value must lie in (lo, hi)
ok = func(node *TreeNode, lo, hi int) bool {
if node == nil {
return true
}
if node.Val <= lo || node.Val >= hi {
return false
}
return ok(node.Left, lo, node.Val) && ok(node.Right, node.Val, hi)
}
return ok(root, math.MinInt, math.MaxInt)
}