Overview
Tree DP often involves computing a state for a node based on the states of its children. This is naturally done using a post-order traversal (DFS).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Compute the longest path (diameter) between any two nodes in a tree using Post-Order Traversal.
Tree DP often involves computing a state for a node based on the states of its children. This is naturally done using a post-order traversal (DFS).
The height of a node is the length of the longest path from it down to a leaf. `height(u) = max(height(children)) + 1`.
The diameter path must "peak" at some node. The longest path peaking at node `u` is exactly the sum of the heights of its two tallest subtrees.
We compute the heights and update the global diameter simultaneously in one pass, avoiding repeated DFS calls.