Graph Theory37 sections · 1633 units
Open in Course

Edge Cases (Small trees)

(n=1 and n=2)

If n=1n=1, the tree is a single node with no edges. The answer for that node is 00 because the sum of distances to itself is 00. No DFS needed, return 00. If n=2n=2, the tree is a single edge connecting two nodes. Answer for each node is 11 because the distance to the other node is 11.

Down pass computes this immediately. Always test these small cases. They often reveal off-by-one errors in your recurrence formula, especially in the up[v] calculation where you add or subtract sizes.