Answers that climb up: lowest common ancestor and the maximum path sum
🌍 In real life. In a family tree, two cousins share many ancestors, but only one of them is the closest: the grandparent where their two branches join. And on a network of hill trails shaped like a tree, each stop has a score (a view is +, a steep climb is −); the best walk can start and end anywhere, as long as it doesn't turn back on itself.
Both are answered the same way: each node asks its two children, then decides, and passes one number or node up to its parent. That is a postorder walk (Lesson 47.2): children first, then the node.
The idea in one sentence: a postorder function returns something small up the tree ("I found p or q", or "the best path going down from me") and, while it is at a node, looks at both children's answers together to update the overall answer.
Its words:
- ancestor: a node on the path from the root down to a node; a node counts as its own ancestor
- lowest common ancestor (LCA): the deepest node that is an ancestor of both p and q
- path: nodes joined by edges, never visiting one twice; it can bend once at its highest node
- gain: the best sum of a path that starts at a node and goes only downwards
Step by step, the LCA of 6 and 2:
- The leaves 6 and 2 are p and q themselves, so they return themselves.
- Node 5 hears "found" from both sides: 5 is where the two branches meet, so it returns itself.
- Node 1's side finds nothing and returns None.
- The root 3 hears 5 from the left and nothing from the right, so it passes 5 up: the LCA is 5.
Watch the postorder: every node is visited only after both of its children have answered.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lca(node, p, q):
if node is None or node.val in (p, q):
return node # nothing here, or one of the two itself
left = lca(node.left, p, q)
right = lca(node.right, p, q)
if left and right: # one on each side: this is the meeting point
return node
return left or right # pass up whichever side found something
root = Node(3, Node(5, Node(6), Node(2)), Node(1, Node(0), Node(8)))
print(lca(root, 6, 2).val, lca(root, 6, 8).val, lca(root, 5, 6).val)The maximum path sum (LeetCode 124). Here the value passed up is a gain: the best sum of a path that starts at this node and goes down one side. At each node:
- Ask both children for their gains; a negative gain is replaced by 0 (better to leave that side out).
- A path that bends here uses both:
node.val + left + right. Compare it with the best so far. - Pass up
node.val + max(left, right): a path continuing up to the parent can take only one side, or it would fork.
Watch the classic tree [-10, 9, 20, null, null, 15, 7]: the best path is 15 → 20 → 7 = 42, which does not go through the root.
Why it is correct. Every path has one highest node, where it bends (or simply starts). At that node, the best such path is the node plus the best non-negative gain from each side, which is exactly what the function compares; every node is tried, so the best path is found. For the LCA: p and q are in different subtrees of their LCA (or the LCA is one of them), so the LCA is the only node that hears from both sides or is itself p or q with the other below it, and every node above it hears from just one side and passes that answer up unchanged.
What it costs, by counting. Each function visits every node once and does O(1) work there: O(n) time, and O(h) memory for the call stack, where h is the tree's height. In a binary search tree the LCA is even quicker: walk down from the root, going left while both values are smaller and right while both are larger; the first node between them is the LCA, O(h).
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_path_sum(root):
best = float("-inf")
def down(node): # the best path that starts here and goes down
nonlocal best
if node is None:
return 0
left = max(down(node.left), 0) # a negative side is better left out
right = max(down(node.right), 0)
best = max(best, node.val + left + right)
return node.val + max(left, right)
down(root)
return best
print(max_path_sum(Node(-10, Node(9), Node(20, Node(15), Node(7)))))
print(max_path_sum(Node(-3)), max_path_sum(Node(2, Node(-1), Node(3))))Mistakes and edge cases.
- Passing both sides up. Returning
node.val + left + rightto the parent lets a path fork; the answer comes out too big. Return one side; compare both sides only locally. - Starting best at 0. For a tree of only negative numbers the answer is the biggest single node (say −3), not 0.
- Not dropping negative gains. Without
max(..., 0)a path is forced to take a side that lowers its sum. - Checking for both p and q before returning. Stopping as soon as a node is p or q is correct even if the other is below it, because then that node is the LCA.
- Very deep trees. A tree shaped like a line, 5,000 nodes deep, passes Python's recursion limit:
RecursionError: maximum recursion depth exceeded. Lesson 47.7 walks a tree with your own stack instead.
Quiz
What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def lca(node, p, q): if node is None or node.val in (p, q): return node # nothing here, or one of the two itself left = lca(node.left, p, q) right = lca(node.right, p, q) if left and right: # one on each side: this is the meeting point return node return left or right # pass up whichever side found something root = Node(3, Node(5, Node(6), Node(2)), Node(1, Node(0), Node(8))) print(lca(root, 0, 8).val, lca(root, 2, 1).val)In the maximum path sum, why does a node pass up node.val + max(left, right) instead of node.val + left + right?
- A path that goes on up to the parent can only use one side, or it would fork
- To make the numbers smaller
- Because the right side is always better
How long do lca and max_path_sum take on a tree of n nodes and height h?
- O(n) time and O(h) stack memory
- O(n²) time
- O(log n) time
lca(root, 6, 2) should be 5, but this gives 3 for the tree Node(3, Node(5, Node(6), Node(2)), Node(1, Node(0), Node(8))). Which line is wrong?
def lca(node, p, q): if node is None or node.val in (p, q): return node left = lca(node.left, p, q) right = lca(node.right, p, q) if left or right: return node return left or right
Coding tasks
Write
lca(node, p, q): the value of the lowest common ancestor of the nodes with valuespandq(both are in the tree, and values are all different).Write
max_path_sum(root): the biggest sum of any path in the tree (a path goes along edges, visits each node at most once, and has at least one node).