RecapDifficulty: Advanced1 min

Recap: Tree Patterns

Pass down what the path knows, return up what the subtree holds, record what bends through a node, and use a queue when the levels are the answer.

A tree pattern decides three things for one recursive visit: what each call is handed by its parent, what it hands back, and what it records on the way. A question about the path to a node passes values down, a question about what lies below returns them up, and a question about the levels themselves uses a queue. Heights and depths count edges throughout:

Tree questions and what each call passes, returns and records
QuestionPassed downReturned upRecordedTraversalCost
Depth of every nodeDepthNothingEach depthRecursion, node firstO(n)
Height of the treeNothingHeight, −1 when emptyNothingRecursion, children firstO(n)
Longest pathNothingHeightLeft + right + 2Recursion, children firstO(n) time, O(h) stack
Lowest common ancestorThe two nodesFound node or nothingNothingRecursion, stops at a targetO(n)
Each level as a groupNothingNothingQueue size per levelQueue, level by levelO(n) time, O(w) space
Save and rebuildNothingThe subtree builtThe line, # for emptyPreorder with markersO(n)

Measuring a height at every node instead of returning it costs O(n²) on a chain, and returning the bent path instead of the height reports a path that cannot exist. Recursion on a chain-shaped tree is as deep as the tree, so a very deep tree in Python needs a stack of its own or a queue.