Validate Binary Search Tree
Difficulty: Medium · Pattern: Trees & BST · LeetCode #98
Return true if the 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 are strictly larger, and both subtrees are BSTs themselves.
Examples
text
[2, 1, 3] → true
[5, 1, 4, null, null, 3, 6] → false (4 < 5 in the right subtree)
[5, 4, 6, null, null, 3, 7] → false (3 is in 5's right subtree)Hints
- Checking only
left.val < node.val < right.valis not enough. See the third example. - Each node must lie within a range inherited from its ancestors.
- Alternatively: an in-order traversal of a BST is strictly increasing.
Approach
Top-down DFS with bounds: the root may be anything in (−∞, +∞). Going left, the upper bound becomes the parent's value; going right, the lower bound becomes the parent's value. If any node falls outside its (lo, hi) range, the tree is invalid.
Alternative: in-order traversal, checking that each value is greater than the previous one.
Complexity
Time: O(n). Space: O(h).
Python solution
def isValidBST(root):
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'))JavaScript solution
function isValidBST(root) {
const ok = (node, lo, hi) => {
if (!node) return true;
if (!(lo < node.val && node.val < hi)) return false;
return ok(node.left, lo, node.val) && ok(node.right, node.val, hi);
};
return ok(root, -Infinity, Infinity);
}