Validate Binary Search Tree
The problem
Section titled “The problem”You get the root of a binary tree. Return whether it 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.
root = [5, 1, 4, null, null, 3, 6] -> falseThe right child 4 is smaller than the root 5, so the tree is invalid.
Key insight
Section titled “Key insight”The tempting check is local: is left.val < node.val < right.val? That is wrong. In
[10, 5, 15, null, null, 6, 20] every parent-child pair looks fine, but 6 sits in the
right subtree of 10 and is smaller than 10.
The rule applies to every ancestor, not just the parent. So carry the allowed range
down the recursion as (low, high). Going left, the current value becomes the new upper
bound. Going right, it becomes the new lower bound. Each node must fall strictly inside
its range.
Show solutionHide solution
def is_valid_bst(root: TreeNode | None) -> bool: def check(node: TreeNode | None, low: float, high: float) -> bool: if node is None: return True if not (low < node.val < high): # strict: equal values are invalid return False return check(node.left, low, node.val) and check(node.right, node.val, high)
return check(root, float("-inf"), float("inf"))export function isValidBST(root: TreeNode | null): boolean { function check(node: TreeNode | null, low: number, high: number): boolean { if (node === null) return true; if (!(low < node.val && node.val < high)) return false; // strict: equal values are invalid return check(node.left, low, node.val) && check(node.right, node.val, high); } return check(root, -Infinity, Infinity);}class Solution { public boolean isValidBST(TreeNode root) { return check(root, Long.MIN_VALUE, Long.MAX_VALUE); // long: node values can be Integer.MIN/MAX }
private boolean check(TreeNode node, long low, long high) { if (node == null) return true; if (node.val <= low || node.val >= high) return false; // strict: equal values are invalid return check(node.left, low, node.val) && check(node.right, node.val, high); }}Complexity
Section titled “Complexity”- Time: O(n) — every node is visited once and does O(1) work.
- Space: O(h) — recursion stack depth equals the tree height
h. That is O(log n) for a balanced tree and O(n) for a skewed one.
Watch out for
Section titled “Watch out for”- Only comparing with the parent. This passes the easy examples and fails the deep violation above. Always pass bounds down.
- Equal values are invalid. Use strict comparisons.
[2, 2, 2]must return false. - Initial bounds. Node values can be the 32-bit int min or max, so starting from
Integer.MIN_VALUEandInteger.MAX_VALUEbreaks. Uselongin Java, or infinities in Python and TypeScript. (You can also usenullbounds.)
Variations
Section titled “Variations”Kth Smallest Element in a BST (LeetCode 230)
Section titled “Kth Smallest Element in a BST (LeetCode 230)”Return the k-th smallest value. The trick: an inorder traversal of a BST visits values in sorted order, so stop at the k-th node visited. Validate BST has an inorder version too: the walk must be strictly increasing.
Recover Binary Search Tree (LeetCode 99)
Section titled “Recover Binary Search Tree (LeetCode 99)”Exactly two nodes were swapped by mistake; fix the tree without changing its shape. The trick: inorder traversal should be increasing. Find the places where it decreases: the first offender is the larger value of the first drop, the second offender is the smaller value of the last drop. Swap their values.
Convert Sorted Array to Binary Search Tree (LeetCode 108)
Section titled “Convert Sorted Array to Binary Search Tree (LeetCode 108)”Build a height-balanced BST from a sorted array. The trick: pick the middle element as the root and recurse on the left and right halves.