Path problems, lowest common ancestor, rebuilding and serialising trees, BST delete, tree-as-graph BFS and prefix sums on paths.
17 min read0/5 questions
Once you can write the recursive template from Trees, interviewers move on to the second tier: the maximum path sum, the lowest common ancestor of two employees in an org chart, saving a tree to a string and loading it back, deleting from a BST, finding every node k steps away. None of these need new data structures. Each needs one small idea that is hard to invent under time pressure and easy once you have seen it.
At work the same ideas show up in plain clothes. A permissions system finds the nearest common group of two users. A UI framework serialises a component tree for server rendering and rebuilds it on the client. A file browser computes folder sizes bottom up and reports the largest along the way. This lesson gives you each idea, why it works, and a tested solution.
Return one thing, record another
The template in Trees returns the answer for a subtree: height, size, "is it balanced". Some problems need an answer that does not pass through the parent. The longest path in a tree might bend at some node deep in the left subtree, going down both sides of it, and a path that bends cannot be extended upward.
The fix is to separate two values:
Return what the parent can use: the best path that goes down one side from this node.
Record (in a variable outside the recursion) the best answer that bends at this node: left arm, plus the node, plus right arm.
Diameter of a Binary Tree returns the height and records left_height + right_height, the number of edges in the longest path bending here. Binary Tree Maximum Path Sum returns the best downward gain and records node.val + left_gain + right_gain. Values can be negative, so a child's gain is clipped with max(0, gain): if an arm would lower the sum, just do not take it. Longest Univalue Path returns the longest same-value arm, which drops to zero whenever the child's value differs.
Maximum path sum on [-10, 9, 20, null, null, 15, 7]
result: best = 9
Post-order, so leaves first. Node 9: both arms are 0. Record 9 + 0 + 0 = 9. Return 9 to the parent.
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef build(values): """Level-order list with None for gaps, the format interview problems use.""" if not values or values[0] is None: return None root = TreeNode(values[0]) queue, i = deque([root]), 1 while queue and i < len(values): node = queue.popleft() for side in ("left", "right"): if i < len(values) and values[i] is not None: child = TreeNode(values[i]) setattr(node, side, child) queue.append(child) i += 1 return rootdef diameter(root): best = 0 def height(node): nonlocal best if node is None: return 0 left, right = height(node.left), height(node.right) best = max(best, left + right) # record: edges on the path bending here return 1 + max(left, right) # return: height, for the parent height(root) return bestdef max_path_sum(root): best = float("-inf") # not 0: every value may be negative def gain(node): nonlocal best if node is None: return 0 left = max(0, gain(node.left)) # drop an arm that would lower the sum right = max(0, gain(node.right)) best = max(best, node.val + left + right) return node.val + max(left, right) gain(root) return bestdef longest_univalue_path(root): best = 0 def arm(node): nonlocal best if node is None: return 0 left, right = arm(node.left), arm(node.right) left = left + 1 if node.left and node.left.val == node.val else 0 right = right + 1 if node.right and node.right.val == node.val else 0 best = max(best, left + right) return max(left, right) arm(root) return bestassert diameter(build([1, 2, 3, 4, 5])) == 3assert diameter(build([1, 2])) == 1assert max_path_sum(build([1, 2, 3])) == 6assert max_path_sum(build([-10, 9, 20, None, None, 15, 7])) == 42assert max_path_sum(build([-3])) == -3assert max_path_sum(build([2, -1])) == 2assert longest_univalue_path(build([5, 4, 5, 1, 1, None, 5])) == 2assert longest_univalue_path(build([1, 4, 5, 4, 4, None, 5])) == 2print(max_path_sum(build([-10, 9, 20, None, None, 15, 7])))
Output
Press Run (⌘ Enter) to see what happens.
In Python, nonlocal lets the inner function update best. In an interview, a one-element list or an instance attribute works too. What matters is saying out loud which value is returned and which is recorded, because mixing them up is the bug in nearly every wrong answer to these problems.
Predict the outputPython
Using build and max_path_sum above, what does this print?
print(max_path_sum(build([-2, -1])))
Need a nudge? Hints walk you through it.
Lowest common ancestor
The lowest common ancestor (LCA) of two nodes is the deepest node that has both of them in its subtree (a node counts as its own ancestor). There are three versions, and naming which one you are solving is half the answer.
In a BST, use the ordering. If both values are smaller than the current node, the LCA is on the left. If both are larger, it is on the right. Otherwise they split here (or one of them is this node), so this node is the LCA. That is O(h) time and O(1) space, with no recursion.
In a general binary tree, there is no ordering to steer by. Ask each subtree "did you find p or q?". A call returns the node if it is p or q, otherwise whatever its children found. If both children report something, p and q are on different sides, and the current node is the LCA.
LCA of 6 and 4 in a general tree
result: 6 returns 6
The call on 6 sees a target and returns it straight away, without searching below it.
1/5
With parent pointers (common in real code, such as DOM nodes or an org chart table with a manager_id column), you do not need the root at all. Walk two pointers upward. When one runs off the top, restart it at the other starting node. Both pointers then travel the same total distance and meet at the LCA. This is the same trick as finding where two linked lists intersect.
from collections import dequeclass TreeNode: def __init__(self, val): self.val, self.left, self.right, self.parent = val, None, None, Nonedef build(values): root = TreeNode(values[0]) queue, i = deque([root]), 1 while queue and i < len(values): node = queue.popleft() for side in ("left", "right"): if i < len(values) and values[i] is not None: child = TreeNode(values[i]) child.parent = node setattr(node, side, child) queue.append(child) i += 1 return rootdef find(root, val): stack = [root] while stack: node = stack.pop() if node.val == val: return node stack.extend(c for c in (node.left, node.right) if c)def lca_bst(root, p, q): node = root while node: if p < node.val and q < node.val: node = node.left elif p > node.val and q > node.val: node = node.right else: return node # they split here, or one of them is heredef lca(root, p, q): """Assumes both p and q are in the tree.""" if root is None or root.val in (p, q): return root left = lca(root.left, p, q) right = lca(root.right, p, q) if left and right: return root # one target on each side return left or rightdef lca_with_parents(a, b): x, y = a, b while x is not y: x = x.parent if x else b # ran off the top: restart at the other node y = y.parent if y else a return xbst = build([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])assert lca_bst(bst, 2, 8).val == 6assert lca_bst(bst, 2, 4).val == 2assert lca_bst(bst, 3, 5).val == 4tree = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])assert lca(tree, 5, 1).val == 3assert lca(tree, 6, 4).val == 5assert lca(tree, 5, 4).val == 5 # a node is its own ancestorfor p, q in [(5, 1), (6, 4), (5, 4), (7, 8), (0, 8)]: assert lca_with_parents(find(tree, p), find(tree, q)) is lca(tree, p, q)print("LCA of 6 and 4:", lca(tree, 6, 4).val)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
You call the general lca(root, 5, 99) on a tree that contains 5 but not 99. What happens?
Need a nudge? A hint rules out a wrong answer.
BST checks: bounds and early stopping
Trees showed why comparing a node only with its parent is not enough to validate a BST: the rule covers whole subtrees. The fix is to pass a (low, high) range down. Going left, the current value becomes the new upper bound. Going right, it becomes the new lower bound.
Two details separate a correct answer from a nearly correct one. First, use None (or null) for "no bound" rather than infinity. In Java or C++, a node may legitimately hold Integer.MAX_VALUE, and a sentinel bound of that same value wrongly rejects it. Second, ask about duplicates. LeetCode's version requires strict inequality on both sides, but a real BST library may put equal keys on one side, and your comparisons must match that policy.
An in-order walk gives a second check: values must come out strictly increasing. It also solves Kth Smallest Element in a BST. Walk in-order with an explicit stack and stop at the k-th pop: O(h + k) time, not O(n). If the tree changes often and the question is asked often, store a subtree size in every node; then you can steer left or right by size and answer in O(h).
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef build(values): if not values: return None root = TreeNode(values[0]) queue, i = deque([root]), 1 while queue and i < len(values): node = queue.popleft() for side in ("left", "right"): if i < len(values) and values[i] is not None: child = TreeNode(values[i]) setattr(node, side, child) queue.append(child) i += 1 return rootdef parent_only_check(node): """The classic WRONG answer: only compares with direct children.""" if node is None: return True if node.left and node.left.val >= node.val: return False if node.right and node.right.val <= node.val: return False return parent_only_check(node.left) and parent_only_check(node.right)def is_bst(root): stack = [(root, None, None)] # (node, low, high); None means no bound while stack: node, low, high = stack.pop() if node is None: continue if (low is not None and node.val <= low) or (high is not None and node.val >= high): return False stack.append((node.left, low, node.val)) stack.append((node.right, node.val, high)) return Truedef kth_smallest(root, k): stack, node = [], root while stack or node: while node: # go as far left as possible stack.append(node) node = node.left node = stack.pop() k -= 1 if k == 0: return node.val # stop early: no need to visit the rest node = node.righttricky = build([5, 3, 8, None, 6]) # 6 is under 5's LEFT sideassert parent_only_check(tricky) is True # fooledassert is_bst(tricky) is Falseassert is_bst(build([4, 2, 6, 1, 3, 5, 7]))assert not is_bst(build([2, 2, 2])) # strict: duplicates are invalid hereassert is_bst(build([2**31 - 1])) # no sentinel to collide withbst = build([5, 3, 6, 2, 4, None, None, 1])assert [kth_smallest(bst, k) for k in range(1, 7)] == [1, 2, 3, 4, 5, 6]print("valid:", is_bst(tricky), " 3rd smallest:", kth_smallest(bst, 3))
Output
Press Run (⌘ Enter) to see what happens.
Rebuilding and serialising trees
Construct Binary Tree from Preorder and Inorder Traversal relies on what each order tells you. Pre-order lists a root before its subtrees, so preorder[0] is the root. In-order lists the left subtree, then the root, then the right subtree, so the root's position in the in-order list tells you exactly how many nodes are on the left.
Recurse with that. The naive version searches the in-order list for each root, which is O(n) per node and O(n²) for a skewed tree. Build a value-to-index map once, and consume pre-order with a single moving pointer (always build left before right, matching pre-order), and the whole thing is O(n). This needs unique values; with duplicates the in-order position is ambiguous.
Serialize and Deserialize Binary Tree is easier than it looks once you see why one traversal is enough here. A plain pre-order list is ambiguous: [1, 2] could be 2 as a left child or as a right child. Add a marker for every missing child and the ambiguity disappears, because the reader knows exactly when each subtree ends. Pre-order with # markers is short to write, handles negatives and duplicates, and reads back with one recursive function that consumes tokens in the same order.
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef preorder(n): return [n.val] + preorder(n.left) + preorder(n.right) if n else []def inorder(n): return inorder(n.left) + [n.val] + inorder(n.right) if n else []def build_tree(pre, ino): index = {v: i for i, v in enumerate(ino)} next_root = iter(pre) def make(lo, hi): # builds the subtree for ino[lo:hi] if lo >= hi: return None val = next(next_root) node = TreeNode(val) mid = index[val] node.left = make(lo, mid) # left first, matching pre-order node.right = make(mid + 1, hi) return node return make(0, len(ino))def serialize(root): out = [] def go(n): if n is None: out.append("#") return out.append(str(n.val)) go(n.left) go(n.right) go(root) return ",".join(out)def deserialize(data): tokens = iter(data.split(",")) def go(): t = next(tokens) if t == "#": return None node = TreeNode(int(t)) node.left = go() node.right = go() return node return go()root = build_tree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])assert preorder(root) == [3, 9, 20, 15, 7] and inorder(root) == [9, 3, 15, 20, 7]assert root.right.left.val == 15t = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))s = serialize(t)assert s == "1,2,#,#,3,4,#,#,5,#,#"assert serialize(deserialize(s)) == sdup = TreeNode(-1, TreeNode(-1, None, TreeNode(-1)))assert serialize(deserialize(serialize(dup))) == "-1,-1,#,-1,#,#,#"assert serialize(None) == "#" and deserialize("#") is Noneprint(s)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Why can you rebuild a tree from pre-order plus # null markers alone, but not from a plain pre-order list?
Need a nudge? A hint rules out a wrong answer.
BST insert and delete
Insert walks down as in search and hangs the new node where the search falls off the tree. Delete has three cases:
No children: remove the node (return None to the parent).
One child: replace the node with that child.
Two children: find the in-order successor, the smallest value in the right subtree (go right once, then left as far as possible). Copy its value into the node, then delete the successor from the right subtree. The successor has no left child by construction, so that second delete is always case 1 or 2.
Writing both functions to return the new subtree root (root.left = delete(root.left, key)) keeps parent bookkeeping out of your code. It is the cleanest way to handle the case where the deleted node is the root.
Delete 50 (two children)
50 has two children, so it cannot simply be removed without orphaning a subtree.
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef insert(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) elif val > root.val: root.right = insert(root.right, val) return root # duplicates are ignoreddef delete(root, key): if root is None: return None # key not found: nothing changes if key < root.val: root.left = delete(root.left, key) elif key > root.val: root.right = delete(root.right, key) else: if root.left is None: return root.right # covers the no-children case too if root.right is None: return root.left succ = root.right while succ.left: succ = succ.left root.val = succ.val root.right = delete(root.right, succ.val) return rootdef level_order(root): out, queue = [], deque([root] if root else []) while queue: node = queue.popleft() out.append(node.val) queue.extend(c for c in (node.left, node.right) if c) return outroot = Nonefor v in [50, 30, 70, 20, 40, 60, 80, 65]: root = insert(root, v)root = delete(root, 50)assert level_order(root) == [60, 30, 70, 20, 40, 65, 80]root = delete(root, 20) # leafroot = delete(root, 30) # one childassert level_order(root) == [60, 40, 70, 65, 80]root = delete(root, 999) # missing keyassert level_order(root) == [60, 40, 70, 65, 80]single = delete(TreeNode(1), 1)assert single is Noneprint(level_order(root))
Output
Press Run (⌘ Enter) to see what happens.
Put it in order5 steps
Put the steps for deleting a node with two children from a BST in order.
Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
When a tree should be a graph: All Nodes Distance K
All Nodes Distance K in Binary Tree asks for every node exactly k edges from a target. Some of those nodes are above the target or in a sibling subtree, and a tree node has no pointer upward. The clean move is to stop treating it as a tree. One traversal records each node's parent; now every node has up to three neighbours (left, right, parent), and the question is a plain BFS by levels from the target, using the level snapshot from Trees and a seen set because edges now go both ways.
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef build(values): root = TreeNode(values[0]) queue, i = deque([root]), 1 while queue and i < len(values): node = queue.popleft() for side in ("left", "right"): if i < len(values) and values[i] is not None: child = TreeNode(values[i]) setattr(node, side, child) queue.append(child) i += 1 return rootdef distance_k(root, target_val, k): parent, target, stack = {root: None}, None, [root] while stack: # pass 1: parent map, and find the target node = stack.pop() if node.val == target_val: target = node for child in (node.left, node.right): if child: parent[child] = node stack.append(child) seen, frontier = {target}, [target] for _ in range(k): # pass 2: BFS, one level per step nxt = [] for node in frontier: for nb in (node.left, node.right, parent[node]): if nb and nb not in seen: seen.add(nb) nxt.append(nb) frontier = nxt return sorted(n.val for n in frontier)tree = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])assert distance_k(tree, 5, 2) == [1, 4, 7]assert distance_k(tree, 5, 0) == [5]assert distance_k(tree, 7, 3) == [3, 6]assert distance_k(tree, 3, 9) == []print(distance_k(tree, 5, 2))
Output
Press Run (⌘ Enter) to see what happens.
The same "add parent edges, then BFS" move solves Amount of Time for Binary Tree to Be Infected and any "nearest leaf to a node" question.
Prefix sums on a root-to-node path: Path Sum III
Path Sum III counts downward paths (any start, any end, always parent to child) that add up to a target. Checking every start node and walking down from it is O(n²) on a skewed tree.
Notice that a downward path is a contiguous slice of some root-to-node path, and that is exactly the subarray-sum-equals-k problem from Prefix Sums and Difference Arrays. Keep the running sum from the root, and a count of each running sum seen on the current path. At a node with running sum s, the number of paths ending here equals counts[s - target]. Seed counts[0] = 1 for paths that start at the root.
The tree-specific part is the backtrack. When recursion leaves a node, decrement its running sum's count. Otherwise a sum from the left subtree would still be in the map while you explore the right subtree, and you would count "paths" that jump sideways between branches.
import randomfrom collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef build(values): root = TreeNode(values[0]) queue, i = deque([root]), 1 while queue and i < len(values): node = queue.popleft() for side in ("left", "right"): if i < len(values) and values[i] is not None: child = TreeNode(values[i]) setattr(node, side, child) queue.append(child) i += 1 return rootdef path_sum_count(root, target): counts = {0: 1} # the empty prefix: paths starting at the root def go(node, running): if node is None: return 0 running += node.val found = counts.get(running - target, 0) counts[running] = counts.get(running, 0) + 1 found += go(node.left, running) + go(node.right, running) counts[running] -= 1 # backtrack: this node leaves the path return found return go(root, 0)def brute(root, target): def down(node, need): # paths starting exactly at node if node is None: return 0 return (node.val == need) + down(node.left, need - node.val) + down(node.right, need - node.val) if root is None: return 0 return down(root, target) + brute(root.left, target) + brute(root.right, target)assert path_sum_count(build([10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]), 8) == 3assert path_sum_count(build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]), 22) == 3assert path_sum_count(build([1, -1, 1]), 0) == 1rng = random.Random(3)for _ in range(300): vals = [rng.choice([None, rng.randint(-3, 3)]) if i else rng.randint(-3, 3) for i in range(rng.randint(1, 15))] t = build(vals) target = rng.randint(-4, 4) assert path_sum_count(t, target) == brute(t, target)print(path_sum_count(build([10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]), 8))
Output
Press Run (⌘ Enter) to see what happens.
Each node does O(1) map work, so this is O(n) time and O(h) extra space for the map and the recursion. Every solution in this lesson recurses once per level, so a skewed tree of 100,000 nodes would exceed Python's default recursion limit of 1,000. The Recursion to Iteration lesson shows how to convert them.
Match the pairs0/6 matched
Match each problem to the idea that cracks it.
Choose an item, then its match on the other side.
Key terms
return vs record
In path problems, the recursive call returns what the parent can extend (one arm) and records the best bent path in an outer variable.
lowest common ancestor
The deepest node with both targets in its subtree. A node counts as its own ancestor.
in-order successor
The next value in sorted order. For a node with a right child, it is the leftmost node of the right subtree.
null marker
A token such as # written for each missing child when serialising. It makes a single pre-order list unambiguous.
parent map
A dictionary from each node to its parent. It turns a tree into an undirected graph so BFS can move upward.
path prefix sum
The running sum from the root to the current node. Counting earlier sums on the same path finds downward paths with a target sum.