Graph Theory37 sections · 1633 units
Open in Course

DP Method - How It Works

Depth through each node

For each node uu, run DFS to compute the depth of each child's subtree. The depth is 11 plus the maximum depth of any child. Track the two deepest child subtrees.

The diameter through node uu is the sum of the two deepest paths going down. Compare this to the global maximum. After processing all nodes, you have the diameter.

This single DFS computes the diameter in O(n)O(n) time. It is useful when you also need subtree information or when the problem combines diameter with other DP states.

Space complexity is O(n)O(n) for the data structures used.