DP on Trees Diameter of Tree in DSA Rust - Time & Space Complexity
We want to understand how long it takes to find the longest path in a tree using dynamic programming.
How does the time needed grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
fn dfs(node: usize, parent: usize, graph: &Vec<Vec<usize>>, max_diameter: &mut usize) -> usize {
let mut max1 = 0;
let mut max2 = 0;
for &child in &graph[node] {
if child == parent { continue; }
let depth = dfs(child, node, graph, max_diameter) + 1;
if depth > max1 {
max2 = max1;
max1 = depth;
} else if depth > max2 {
max2 = depth;
}
}
*max_diameter = (*max_diameter).max(max1 + max2);
max1
}
This code finds the diameter of a tree by exploring each node once and tracking the longest paths.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (DFS) visiting each node.
- How many times: Each node is visited exactly once, and each edge is checked once.
As the number of nodes grows, the number of operations grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and 9 edge checks |
| 100 | About 100 visits and 99 edge checks |
| 1000 | About 1000 visits and 999 edge checks |
Pattern observation: The work grows linearly with the number of nodes.
Time Complexity: O(n)
This means the time to find the diameter grows directly in proportion to the number of nodes in the tree.
[X] Wrong: "Since the code uses recursion inside a loop, it must be quadratic time O(n²)."
[OK] Correct: Each node is visited only once because the recursion skips the parent, so the total work is linear, not quadratic.
Understanding this linear time approach to tree diameter shows you can handle tree problems efficiently, a key skill in many coding challenges.
"What if we changed the tree to a graph with cycles? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of tree diameter
The diameter is the longest path between any two nodes, not just from the root or sum of edges.Step 2: Differentiate from other tree properties
Height is from root to leaf, sum of edges is total weight, number of nodes is size, none equal diameter.Final Answer:
The longest path between any two nodes in the tree -> Option AQuick Check:
Diameter = Longest path [OK]
- Confusing diameter with tree height
- Thinking diameter is total nodes count
- Assuming diameter is sum of all edges
Vec?Solution
Step 1: Identify correct parameter passing for graph
Graph should be passed by reference (&Vec) to avoid copying large data.Step 2: Include parent parameter to avoid revisiting parent node
Parent node is needed to prevent cycles in undirected tree traversal.Final Answer:
fn diameter(node: usize, parent: usize, graph: &Vec) -> usize { ... } -> Option CQuick Check:
Pass graph by reference and track parent [OK]
- Passing graph by value causing performance issues
- Missing parent parameter causing infinite recursion
- Using &mut when mutation is not needed
fn dfs(node: usize, parent: usize, graph: &Vec, max_diameter: &mut usize) -> usize {
let mut max1 = 0;
let mut max2 = 0;
for &child in &graph[node] {
if child == parent { continue; }
let height = dfs(child, node, graph, max_diameter);
if height > max1 {
max2 = max1;
max1 = height;
} else if height > max2 {
max2 = height;
}
}
*max_diameter = (*max_diameter).max(max1 + max2);
max1 + 1
}
fn main() {
let graph = vec![
vec![1, 2],
vec![0, 3, 4],
vec![0],
vec![1],
vec![1]
];
let mut max_diameter = 0;
dfs(0, usize::MAX, &graph, &mut max_diameter);
println!("{}", max_diameter);
}Solution
Step 1: Trace DFS heights from leaves
Leaves 2, 3, 4 return height 1; node 1 gets max1=1, max2=1; node 0 gets max1=2 (from node 1), max2=1 (from node 2).Step 2: Calculate max diameter updates
At node 1, max_diameter = max(0,1+1)=2; at node 0, max_diameter = max(2,2+1)=3.Final Answer:
3 -> Option AQuick Check:
Longest path length = 3 edges [OK]
- Counting nodes instead of edges for diameter
- Not updating max_diameter correctly
- Ignoring parent to avoid revisiting
fn dfs(node: usize, graph: &Vec, max_diameter: &mut usize) -> usize {
let mut max1 = 0;
let mut max2 = 0;
for &child in &graph[node] {
let height = dfs(child, graph, max_diameter);
if height > max1 {
max2 = max1;
max1 = height;
} else if height > max2 {
max2 = height;
}
}
*max_diameter = (*max_diameter).max(max1 + max2);
max1 + 1
}Solution
Step 1: Identify infinite recursion cause
Without parent tracking, dfs revisits parent causing infinite recursion or stack overflow.Step 2: Fix by adding parent parameter
Pass parent node to skip revisiting it in children loop, preventing cycles.Final Answer:
Add a parent parameter to avoid revisiting the parent node -> Option BQuick Check:
Parent tracking prevents infinite recursion [OK]
- Not passing parent causing infinite recursion
- Misusing mutable references for max_diameter
- Incorrect initialization of max heights
Solution
Step 1: Understand weighted tree diameter difference
Diameter must consider edge weights, so heights become max weighted path lengths.Step 2: Modify DP to accumulate weights
Instead of counting edges, add edge weights when computing subtree heights and update max diameter accordingly.Final Answer:
Store and propagate the maximum weighted path length instead of just height counts -> Option DQuick Check:
Weighted diameter needs weighted path sums [OK]
- Ignoring weights leads to wrong diameter
- Using BFS without weights misses weighted paths
- Incorrect formula dividing total weights
Ready to prove it?
Pass the test and this pattern moves unknown
