PrepStack · Markdown HTML

Tree recursive aggregation

Tree, BST, and trie · HTML

Formal shape

dfs(node) returns an identity for null, recursively obtains child summaries, computes upward_summary=combine(value,children), and may update global_answer using two or more child branches.

Recognition signals

False friends

SignalWhy it is different
Layer-based or nearest-depth outputLevel-order BFS directly exposes complete depth boundaries.
Several mutually exclusive modes per nodeWhen one summary is insufficient, use a vector of tree-DP states.
Aggregation paths in a general graphCycles and shared subgraphs break independent subtrees; use graph or DAG machinery.

Core invariant

dfs(u) returns a summary concerning only u's subtree and satisfying its parent contract; before return, every global candidate fully contained in that subtree has been considered.

State, transition, and processing order

ItemDefinition
StateThe current node, child summaries, and either a separate global accumulator or a structured return value.
TransitionRecurse into children, compute node-local complete candidates, update the global answer, and build one upward summary.
Frontier / orderPostorder on the recursion stack; a null identity unifies leaf transitions.

Python skeleton

def tree_diameter(root):
    best = 0
    def height(node):
        nonlocal best
        if node is None:
            return 0
        left = height(node.left)
        right = height(node.right)
        best = max(best, left + right)
        return 1 + max(left, right)
    height(root)
    return best

Correctness sketch

  1. A null subtree has height zero, satisfying the return contract.
  2. Assuming child heights are correct, an upward path through this node can choose only the taller child, so its height is 1+max.
  3. A path whose highest connector is this node uses left+right; every cross-subtree path has one such connector, making the global maximum complete.

Complexity

TimeSpaceParameters
O(n) when combine costs O(node degree)O(h) recursion stack, worst-case O(n)n is node count and h tree height.

Edge cases

Error patterns

PatternWhy it fails / fix
Returning the complete global optimum upwardA path joining two children cannot also extend through the parent; separate complete and extendable values.
Aggregating in preorderChild summaries are unavailable, so the node result is incomplete.
Using the wrong null identityHeight, sum, extrema, and negative path objectives need different neutral values or sentinels.
Rescanning a subtree at every nodeThat turns O(n) into O(n²); return each reusable summary once.

Selection and exclusion rules

RelationTemplateBoundary
traversal-foundationBST ordering / inorder traversalSubtrees return min/max or structural summaries.
generalizationTree dynamic programmingOne summary is insufficient and several node modes must be returned.

Original micro-example

PartDetail
ResultThe complete candidate joins both sides, while the upward summary retains one, so their meanings differ.
SetupA root has a left chain of height 2 and a right chain of height 1.
TraceThe complete path through the root has 2+1=3 edges; the upward summary keeps only one side as height 1+max(2,1)=3.

Recall prompts

My notes