The "Validate Binary Search Tree" interview question asks you to determine if a given binary tree is a valid Binary Search Tree (BST). In a valid BST, for every node, all values in its left subtree must be strictly less than the node's value, and all values in its right subtree must be strictly greater than the node's value.
This "Validate Binary Search Tree" coding problem is a classic at companies like Amazon, Microsoft, and Google. It tests your understanding of tree properties and recursive traversal. It specifically targets a common misconception: that simply checking if a node's children are valid is enough (it isn't; you must check the entire subtree range).
The primary algorithmic pattern is "Depth-First Search (DFS)" with a recursive "Tree interview pattern." You pass a valid range [min, max] down to each node. For the root, the range is [-infinity, +infinity]. When moving left, the max becomes the current node's value. When moving right, the min becomes the current node's value.
Tree: 5 at root, 3 on left, 7 on right, 4 as right child of 3.
(-inf, +inf). 5 is in range.(-inf, 5). 3 is in range.(3, 5). 4 is in range.(5, +inf). 7 is in range.A common mistake is only checking node.left.val < node.val < node.right.val. This fails for a tree where a node deep in the left subtree is greater than the root. Another error is using Integer.MIN_VALUE or MAX_VALUE as boundaries, which fails if the tree actually contains those values. Using null or a specialized wrapper to represent infinity is safer.
For the "Validate Binary Search Tree" coding problem, an alternative approach is to perform an In-order traversal. In a valid BST, an in-order traversal should yield values in strictly increasing order. If you encounter a value that is less than or equal to the previous one, the tree is not a valid BST. This is often easier to implement and reason about.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Lowest Common Ancestor of a Binary Search Tree | Medium | Solve | |
| Kth Smallest Element in a BST | Medium | Solve | |
| Recover Binary Search Tree | Medium | Solve | |
| Binary Search Tree to Greater Sum Tree | Medium | Solve | |
| Inorder Successor in BST | Medium | Solve |