Module 3 · Drill 1 · tree reps
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?"
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.
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.
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;
}
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);
}
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;
}