Dynamic Programming21 sections · 916 units
Open in Course

Tree Diameter - Walkthrough

Tracing the algorithm

Trace diameter on a tree: 11-22-33-44 with 55 attached to 22. The diameter is the path 44-33-22-55 or 44-33-22-11 (length 33). At each node, compute depth1depth1 and depth2depth2 = two longest paths going down.

The candidate diameter through this node is depth1+depth2depth1 + depth2. At node 22: paths down are to 11 (length 11), to 55 (length 11), and to 33-44 (length 22). Two longest: 22 and 11. Candidate: 2+1=32 + 1 = 3. The global maximum of all candidates gives the diameter. Post-order traversal keeps children are processed before parents.