1. Empty is valid
An empty subtree never violates the BST rule.
if (node === null) {
return true;
}Typorithm · medium
Step 1 of 8 · intro card
Trees
Recurse with an open (low, high) interval; each node must fall strictly inside, tightening bounds going down.
A BST requires every node greater than all left-subtree values and less than all right-subtree values — not just its direct children.
Carry a valid (low, high) range and check each node against it.
Going left tightens the upper bound to the node's value; going right tightens the lower bound.
Pass a (low, high) range down.
Left tightens high, right tightens low.
Start with -Infinity and Infinity.
function isValidBST(root) {
function valid(node, low, high) {
if (node === null) {
return true;
}
if (node.val <= low || node.val >= high) {
return false;
}
return valid(node.left, low, node.val) && valid(node.right, node.val, high);
}
return valid(root, -Infinity, Infinity);
}Connect each part of the code to the concept before you type.
An empty subtree never violates the BST rule.
if (node === null) {
return true;
}The value must lie strictly inside the open interval.
if (node.val <= low || node.val >= high)Left children must be below this node's value.
valid(node.left, low, node.val)Right children must be above this node's value.
valid(node.right, node.val, high)The root may be any value, so start with infinite bounds.
valid(root, -Infinity, Infinity)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.