Problem Statement
Given the root of a binary tree, determine if it is a valid Binary Search Tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Approach: Recursive Range Validation
A common mistake is only checking if a node is larger than its direct left child and smaller than its direct right child. You must ensure every node in the left subtree is smaller than the parent.
- Helper Function: Use a recursive function
validate(node, min, max). - Boundaries:
- When moving left, update the
maxboundary to the current node's value. - When moving right, update the
minboundary to the current node's value.
- When moving left, update the
- Check: If
node.val <= minornode.val >= max, returnfalse.
Java Implementation
public boolean isValidBST(TreeNode root) {
return validate(root, null, null);
}
private boolean validate(TreeNode node, Integer min, Integer max) {
if (node == null) return true;
if ((min != null && node.val <= min) || (max != null && node.val >= max)) {
return false;
}
return validate(node.left, min, node.val) &&
validate(node.right, node.val, max);
}
Complexity Analysis
- Time Complexity: $O(n)$.
- Space Complexity: $O(h)$ for the recursion stack.
Interview Tips
- Mention the In-order Traversal trick: A BST's in-order traversal results in a sorted list. You can validate it by checking if the sequence is strictly increasing.