Q18: Validate Binary Search Tree
Determine if a given binary tree is a valid Binary Search Tree (BST) where left subtree values are strictly smaller and right subtree values are strictly larger than root.
BST Boundary Range Validation
function isValidBST(root, min = null, max = null) {
if (root === null) return true;
if ((min !== null && root.val <= min) || (max !== null && root.val >= max)) {
return false;
}
return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
}Validates node value against allowable min and max constraints. When stepping left, updates max bound to current node value; when stepping right, updates min bound.
Key Takeaways
Pass lower and upper boundary bounds recursively during DFS traversal.
Checking only immediate child nodes is insufficient; subtrees must satisfy full boundary limits.
Knowledge Check
Why is checking if root.left.val < root.val and root.right.val > root.val insufficient for verifying a BST?