Tree Traversal & BST · 15 min · free lesson

Challenge: Tree Rerooting DP

Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.

Core idea

Distances decrease for the moved-into subtree and increase for all other nodes. Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Compute child-to-parent contributions, then propagate the outside contribution while changing the root.

O(n) time · O(n) space40 execution steps
main · before line 37Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputn=3 edges=(0,1),(1,2)

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 37
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn distance_sums(graph: &[Vec<usize>]) -> Vec<usize> {
    fn collect(v: usize, parent: usize, g: &[Vec<usize>], size: &mut [usize], down: &mut [usize]) {
        size[v] = 1;
        for &u in &g[v] {
            if u != parent {
                collect(u, v, g, size, down);
                size[v] += size[u];
                down[v] += down[u] + size[u];
            }
        }
    }
    fn reroot(v: usize, parent: usize, g: &[Vec<usize>], size: &[usize], answer: &mut [usize]) {
        for &u in &g[v] {
            if u != parent {
                answer[u] = answer[v] + g.len() - 2 * size[u];
                reroot(u, v, g, size, answer);
            }
        }
    }
    let n = graph.len();
    if n == 0 {
        return Vec::new();
    }
    let (mut size, mut answer) = (vec![0; n], vec![0; n]);
    collect(0, n, graph, &mut size, &mut answer);
    reroot(0, n, graph, &size, &mut answer);
    answer
}
 
fn main() {
    let result = csv(distance_sums(&[vec![1], vec![0, 2], vec![1]]));
    println!("{result}");
}

Try your own version

Change the independent fixture `n=3 edges=(0,1),(1,2)` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `n=4 edges=(0,1),(1,2),(1,3)`.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Tree Traversal & BST infographic; panel 5 illustrates Tree Rerooting.
Tree Rerooting: follow panel 5 to see the operation, then trace this lesson's example.

Understand it

Distances decrease for the moved-into subtree and increase for all other nodes. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input n=3 edges=(0,1),(1,2), the worked program returns 3,2,3. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input n=4 edges=(0,1),(1,2),(1,3); predict that result before opening the answer reveal. The precise contract is: Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order. On input n=4 edges=(0,1),(1,2),(1,3), predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Compute child-to-parent contributions, then propagate the outside contribution while changing the root. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A tree result is built from a node and its children. Decide whether information flows downward, upward, or in level order. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(n) time · O(n) space; explain which operation dominates it and how many times the input can trigger that operation. Test a missing root, a leaf, a skewed tree, and equal or duplicate values when ordering rules depend on them. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

The pattern

Compute child-to-parent contributions, then propagate the outside contribution while changing the root.

When to use it: all-node distance sums and per-root tree answers

Complexity: O(n) time · O(n) space

Input: n=4 edges=(0,1),(1,2),(1,3)

Read the code

fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
    a.into_iter()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join(",")
}
fn distance_sums(graph: &[Vec<usize>]) -> Vec<usize> {
    fn collect(v: usize, parent: usize, g: &[Vec<usize>], size: &mut [usize], down: &mut [usize]) {
        size[v] = 1;
        for &u in &g[v] {
            if u != parent {
                collect(u, v, g, size, down);
                size[v] += size[u];
                down[v] += down[u] + size[u];
            }
        }
    }
    fn reroot(v: usize, parent: usize, g: &[Vec<usize>], size: &[usize], answer: &mut [usize]) {
        for &u in &g[v] {
            if u != parent {
                answer[u] = answer[v] + g.len() - 2 * size[u];
                reroot(u, v, g, size, answer);
            }
        }
    }
    let n = graph.len();
    if n == 0 {
        return Vec::new();
    }
    let (mut size, mut answer) = (vec![0; n], vec![0; n]);
    collect(0, n, graph, &mut size, &mut answer);
    reroot(0, n, graph, &size, &mut answer);
    answer
}

fn main() {
    let result = csv(distance_sums(&[vec![1], vec![0, 2], vec![1]]));
    println!("{result}");
}

Complete std-only tree-rerooting program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement tree-rerooting")
}

Try it

Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.

What success looks like: The private harness prints PASS tree-rerooting. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for tree-rerooting: with input n=5 edges=(0,1),(0,2),(0,3),(0,4), what result should solve return?

Reveal the answer
  1. 4,7,7,7,7
  2. 7,7,7,7
  3. 5,7,7,7,7

For this input the result is 4,7,7,7,7. Distances decrease for the moved-into subtree and increase for all other nodes. Compare this independent fixture with the worked trace: With edges 0-1,1-2,1-3, root 0 has distance sum 5. Moving into subtree 1 of size 3 changes the sum by 4-6=-2, giving 3. Moving from 1 to leaf 2 gives 5; the full output is [5,3,5,5].

Go deeper

Common misconception: “Every distance decreases by exactly one”

Distances decrease for the moved-into subtree and increase for all other nodes. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Distances decrease for the moved-into subtree and increase for all other nodes. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses n=3 edges=(0,1),(1,2) and computes 3,2,3. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For n=5 edges=(0,1),(0,2),(0,3),(0,4), the independently calculated result is 4,7,7,7,7. The complexity discussion uses O(n) time · O(n) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture n=3 edges=(0,1),(1,2) in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge n=4 edges=(0,1),(1,2),(1,3).

Connections

  • Tree Rerooting DP: When to Use It: all-node distance sums and per-root tree answers
Reveal the Algorithm Atlas answer

5,3,5,5

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Challenge: Tree Rerooting DP (courseId "algorithms", lessonId "algorithm.tree-rerooting.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.tree-rerooting.challenge
Goal: Distances decrease for the moved-into subtree and increase for all other nodes. Parse n and edges of a connected undirected tree on 0..n-1. Return the sum of distances from each vertex, in vertex order.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.tree-rerooting.challenge) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.