Module 3 · Drill 1 · tree reps

Tree traversal drills

Three problems, all on binary trees represented as {val, left, right} objects (or None). Get these three reflexive and any tree problem becomes "which traversal do I want?"

1 — Inorder traversal (return list of values)

2 — Validate a BST

A binary search tree has the invariant: every node's value is greater than every value in its left subtree and less than every value in its right subtree. Recurse with running min/max bounds.

3 — Lowest Common Ancestor (binary tree, not BST)

Given a binary tree and two node values guaranteed to exist, return the value of their lowest common ancestor. Recursion with "did I find p or q below me?" returns.

Solutions

1 — Inorder traversal

def inorder(root):
    if not root: return []
    return inorder(root['left']) + [root['val']] + inorder(root['right'])

# Iterative version (the one interviewers sometimes ask for)
def inorder_iter(root):
    out, stack = [], []
    cur = root
    while cur or stack:
        while cur:
            stack.append(cur)
            cur = cur['left']
        cur = stack.pop()
        out.append(cur['val'])
        cur = cur['right']
    return out
  
function inorder(root) {
  if (!root) return [];
  return [...inorder(root.left), root.val, ...inorder(root.right)];
}

function inorderIter(root) {
  const out = [], stack = [];
  let cur = root;
  while (cur || stack.length) {
    while (cur) { stack.push(cur); cur = cur.left; }
    cur = stack.pop();
    out.push(cur.val);
    cur = cur.right;
  }
  return out;
}
  
type TreeNode = { val: number; left: TreeNode | null; right: TreeNode | null };

function inorder(root: TreeNode | null): number[] {
  if (!root) return [];
  return [...inorder(root.left), root.val, ...inorder(root.right)];
}

function inorderIter(root: TreeNode | null): number[] {
  const out: number[] = [];
  const stack: TreeNode[] = [];
  let cur = root;
  while (cur || stack.length) {
    while (cur) { stack.push(cur); cur = cur.left; }
    cur = stack.pop()!;
    out.push(cur.val);
    cur = cur.right;
  }
  return out;
}
  
O(n) time, O(h) space for the recursion stack. Recursive is the cleanest answer; iterative is sometimes asked for explicitly. Both visit each node once.

2 — Validate BST

def is_valid_bst(root, lo=float('-inf'), hi=float('inf')):
    if not root: return True
    if not (lo < root['val'] < hi): return False
    return (is_valid_bst(root['left'], lo, root['val']) and
            is_valid_bst(root['right'], root['val'], hi))
  
function isValidBST(root, lo = -Infinity, hi = Infinity) {
  if (!root) return true;
  if (root.val <= lo || root.val >= hi) return false;
  return isValidBST(root.left, lo, root.val) && isValidBST(root.right, root.val, hi);
}
  
type TreeNode = { val: number; left: TreeNode | null; right: TreeNode | null };

function isValidBST(root: TreeNode | null, lo = -Infinity, hi = Infinity): boolean {
  if (!root) return true;
  if (root.val <= lo || root.val >= hi) return false;
  return isValidBST(root.left, lo, root.val) && isValidBST(root.right, root.val, hi);
}
  
O(n) time, O(h) space. The trick: pass running (lo, hi) bounds down the recursion. A naive check that compares each node only to its immediate children fails — for example, a 5 deep in the right subtree of a 10's left subtree would pass that local check but violate the global BST property. Bounds catch this.

3 — Lowest Common Ancestor

def lca(root, p, q):
    if not root: return None
    if root['val'] == p or root['val'] == q:
        return root['val']
    left = lca(root['left'], p, q)
    right = lca(root['right'], p, q)
    if left is not None and right is not None:
        return root['val']    # p and q split here — this is LCA
    return left if left is not None else right
  
function lca(root, p, q) {
  if (!root) return null;
  if (root.val === p || root.val === q) return root.val;
  const left = lca(root.left, p, q);
  const right = lca(root.right, p, q);
  if (left !== null && right !== null) return root.val;
  return left !== null ? left : right;
}
  
type TreeNode = { val: number; left: TreeNode | null; right: TreeNode | null };

function lca(root: TreeNode | null, p: number, q: number): number | null {
  if (!root) return null;
  if (root.val === p || root.val === q) return root.val;
  const left = lca(root.left, p, q);
  const right = lca(root.right, p, q);
  if (left !== null && right !== null) return root.val;
  return left !== null ? left : right;
}
  
O(n) time, O(h) space. Post-order recursion. Each subtree returns "did I find p or q below me?" If both children find one each, this node is the LCA. Otherwise, propagate whichever child found something.