← Questions

Sum of distances from every node in a tree

0
GoogleCodingLast asked Jan 2026

Given an undirected tree with n nodes, return for every node the sum of its distances to all other nodes. A BFS from every node is too slow; compute it in linear time with two passes (subtree sizes, then rerooting).

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding