Tree DFS

Trees & Graphs

Signal

Root-to-leaf path, subtree logic, validation

Template

Recurse; pass bounds/state down.

Worked example (1)

#12

Tree DFS

DFS with bounds

Determine whether a binary tree is a valid binary search tree.

function isValidBST(root: TreeNode | null): boolean {
  const check = (node: TreeNode | null, low: number, high: number): boolean => {
    if (!node) return true;
    if (node.val <= low || node.val >= high) return false;
    return check(node.left, low, node.val) && check(node.right, node.val, high);
  };
  return check(root, -Infinity, Infinity);
}
Insight

Checking only parent-child order is a classic bug; every node must fall within an inherited range.