You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This discussion was converted from issue #32 on September 15, 2026 11:00.
Heading
Bold
Italic
Quote
Code
Link
Numbered list
Unordered list
Task list
Attach files
Mention
Reference
Menu
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Problem link
https://leetcode.com/problems/sum-of-distances-in-tree/
Problem Summary
트리가 주어질 때 각 노드에서 다른 노드까지의 거리의 합을 모두 구하는 문제.
Solution
단순 N^2은 시간 초과이므로 한 번(N)에 구해야 한다.
잘 생각해보면 각 노드의 자식 노드의 개수를 이용하면 된다.
먼저 0번 노드부터 다른 노드까지의 거리를 구해준 다음, 각 노드에서 거리를 구할 땐 자식 노드의 개수를 이용하면 된다.
거리를 계산할 기준 노드를 child로 옮긴다고 생각할 수 있다. 그렇게 되면 기존 자식 노드들은 한 칸 씩 가까워지므로 빼주고 다른 노드들은 한 칸 씩 더 멀어지므로 더해주는 방식으로 계산할 수 있다.
참고) https://leetcode.com/problems/sum-of-distances-in-tree/discuss/1308366/C%2B%2B-solution-using-dfs-with-explanation-O(N)-time-complexity
Source Code
All reactions