Problem 834

Abstract / Summary

Given a tree with nodes and values on them compute for each node the sum of distances to all other nodes

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0834.py

class Solution:
    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        result  = [ 0 ] * n
        subtree = [ 0 ] * n # number of nodes in this subtree (including the node itself)

        tree = defaultdict(list)
        for a, b in edges:
            tree[a].append(b)
            tree[b].append(a)

        def down(node, previous):
            nonlocal subtree, result
            subtree[node] = 1 # at least the current node is in this subtree
            for t in tree[node]:
                if t != previous: # avoid loops
                    down(t, node)
                    subtree[node] += subtree[t]             # add number of all children
                    result [node] += result[t] + subtree[t] # edge to next node has to be walked once per child
                                                            # plus all routes inside the subtree

        def up(node, previous):
            nonlocal subtree, result
            for t in tree[node]:
                if t != previous: # avoid loops
                    sub = result[node] - subtree[t]
                    result[t] = sub + n - subtree[t]
                    up(t, node)

        root    = 0
        invalid = -1
        down(root, invalid)
        up  (root, invalid)
        return result
33 lines | 1339 bytes | submitted December 13, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (200k+ submissions).

Typical patterns to solve this problem:
  • Depth First Search
  • Dynamic Programming
  • Graph Theory
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation computes, for every node in an undirected tree, the sum of distances to all other nodes. It builds an adjacency representation, performs a post-order traversal to gather subtree sizes and partial distance sums, then a pre-order traversal to propagate those sums outward. The result array is filled in a single pass for each direction, yielding an overall linear execution over the number of vertices.

Building the adjacency structure

The code transforms the edge list into a dictionary where each key maps to a list of its neighbours. This structure enables constant-time access to adjacent nodes during the traversals.

tree = defaultdict(list)
for a, b in edges:
    tree[a].append(b)
    tree[b].append(a)

First traversal - gathering subtree information

A depth-first search named down visits each node once, starting from an arbitrary root (node 0). For every node it records the size of its subtree-including the node itself-in subtree[node]. It also accumulates the sum of distances from the node to all nodes in its subtree in result[node]. The recursion skips the node from which it arrived (previous) to avoid revisiting the parent.

def down(node, previous):
    nonlocal subtree, result
    subtree[node] = 1                     # count the node itself
    for t in tree[node]:
        if t != previous:                 # prevent backtracking
            down(t, node)
            subtree[node] += subtree[t]   # add child subtree size
            result[node] += result[t] + subtree[t]

The term result[t] + subtree[t] reflects that every distance inside the child subtree must be increased by one when measured from the current node, because the edge to the child is traversed once for each node in that child subtree.

Second traversal - propagating results outward

After the first pass, each node knows the total distance to nodes in its own subtree. The up function uses this information to compute the distance sum for the rest of the tree. For a child t of node, the distance sum for t equals the distance sum for node minus the contribution of t’s subtree, plus the distance to all nodes outside that subtree. The formula sub + n - subtree[t] captures this adjustment, where sub is the part of node’s result that does not belong to t’s subtree.

def up(node, previous):
    nonlocal subtree, result
    for t in tree[node]:
        if t != previous:                 # avoid revisiting parent
            sub = result[node] - subtree[t]
            result[t] = sub + n - subtree[t]
            up(t, node)

By recursively applying this step, the algorithm fills result for every node without revisiting edges unnecessarily.

Edge-case handling

The algorithm gracefully handles a tree consisting of a single node. In that scenario the adjacency list is empty, the down call sets subtree[0] to 1 and leaves result[0] at 0, while the up call performs no further work, returning [0] as expected.

A linear chain (a path) is processed correctly because each node has at most two neighbours; the previous guard ensures the traversal proceeds in one direction during down and reverses direction during up. The computation of sub and the subsequent assignment to result[t] correctly account for the shifting balance of nodes on either side of the edge.

A star-shaped tree, where one central node connects to all others, also works. The central node’s down phase aggregates the size of each leaf subtree (each of size 1) and the leaf contributions to the distance sum. The up phase then distributes the central node’s total distance to each leaf, adding the distance to all other leaves (n - subtree[t]) while subtracting the leaf’s own contribution.

The sentinel value invalid = -1 passed as the initial previous argument guarantees that the root node has no parent, preventing accidental exclusion of any neighbour during the first call.

Performance optimizations

The code leverages several techniques to keep the execution efficient. Using a defaultdict(list) for the adjacency list avoids explicit existence checks when appending neighbours. The two traversals each visit every edge exactly once, resulting in linear work relative to the number of vertices. The nonlocal declarations allow the inner functions to modify the outer-scope arrays without copying them, reducing overhead. Storing subtree sizes eliminates the need for repeated counting, enabling the distance sums to be updated with simple arithmetic rather than nested loops. The separation of the problem into a bottom-up and a top-down pass avoids redundant calculations and ensures that each node’s final result is derived from already-computed values.

The final return statement delivers the fully populated result list, containing the sum of distances from each node to all others.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a playground where all the jungle gyms are connected by paths in a giant tree shape. Each jungle gym has a number, and you want to know the total length of the paths it takes to visit every other jungle gym starting from your current spot.

First, the code builds the map of all the paths between the jungle gyms so it knows which ones are connected.

Then, there is a helpful little explorer that starts at the top and goes down every branch. As it visits each spot, it counts how many jungle gyms are hidden in the branches below it. It adds up all those little paths so that by the time it reaches the top again, it knows the total distance for that starting spot.

After that, a second explorer starts at the top and goes back through the paths to visit everyone else. This time, it uses the work done by the first explorer to figure out the distances for all the other spots really quickly. Instead of recalculating everything from scratch, it realizes that when you move to a neighbor, the distance changes in a very predictable way based on how many jungle gyms are on one side of the path versus the other.

It keeps zooming around until it has filled in the answers for every single jungle gym on the playground.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.44 | σ = 1.31

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
vthwang Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
vthwang Java
wisdompeak C++
zfang399 C++
31 links | 18 authors | 8 languages

Videos

11 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 solutions   December 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality