DP on Trees Diameter of Tree in DSA C - 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 grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
int diameter = 0;
int dfs(int node, int parent, vector<vector<int>>& adj) {
int max1 = 0, max2 = 0;
for (int child : adj[node]) {
if (child == parent) continue;
int height = dfs(child, node, adj) + 1;
if (height > max1) {
max2 = max1;
max1 = height;
} else if (height > max2) {
max2 = height;
}
}
diameter = max(diameter, max1 + max2);
return max1;
}
// Call dfs(0, -1, adj) to start
This code finds the diameter of a tree by exploring each node and calculating the longest paths down its children.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (DFS) visiting each node once.
- How many times: Each node is visited exactly one time, and each edge is checked once in the adjacency list.
As the number of nodes grows, the DFS visits each node and edge once, so the work grows roughly in direct proportion to the number of nodes and edges.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 nodes and 9 edges visited |
| 100 | About 100 nodes and 99 edges visited |
| 1000 | About 1000 nodes and 999 edges visited |
Pattern observation: The operations increase roughly linearly as the tree size increases.
Time Complexity: O(n)
This means the time to find the diameter grows linearly with the number of nodes in the tree.
[X] Wrong: "The diameter calculation takes quadratic time because it checks pairs of nodes."
[OK] Correct: The code uses DFS to visit each node once, not checking all pairs separately, so it runs in linear time.
Understanding this linear time approach 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 in the tree, not just from the root.Step 2: Differentiate from other tree properties
Height is from root to leaf, sum of edges is total weight, and node count is size, none represent longest path.Final Answer:
The longest path between any two nodes in the tree -> Option DQuick Check:
Diameter = Longest path [OK]
- Confusing diameter with height
- Thinking diameter is number of nodes
- Assuming diameter is sum of all edges
n nodes in C?Solution
Step 1: Understand adjacency list structure
An adjacency list uses an array of pointers to lists (or arrays) of neighbors, so int* adj[n]; is correct.Step 2: Differentiate from other declarations
int adj[n][n]; is adjacency matrix, int adj[n]; is a simple array, int adjList[n][2]; is edge list, not adjacency list.Final Answer:
int* adj[n]; -> Option BQuick Check:
Adjacency list uses array of pointers [OK]
- Using 2D array as adjacency list
- Using simple array for adjacency
- Confusing edge list with adjacency list
int diameter = 0;
int dfs(int node, int parent, vector<int> adj[]) {
int max1 = 0, max2 = 0;
for (int child : adj[node]) {
if (child == parent) continue;
int height = dfs(child, node, adj) + 1;
if (height > max1) {
max2 = max1;
max1 = height;
} else if (height > max2) {
max2 = height;
}
}
diameter = max(diameter, max1 + max2);
return max1;
}
// Call dfs(1, -1, adj) and then print diameter;Solution
Step 1: Trace DFS from node 1
From node 1, child is 2. DFS(2) explores children 3 and 4. Heights from 3 and 4 are 1 each.Step 2: Calculate diameter updates
At node 2, max1=1, max2=1, diameter updated to 2. At node 1, max1=2, max2=0, diameter remains 2.Final Answer:
2 -> Option AQuick Check:
Longest path length = 2 edges [OK]
- Counting nodes instead of edges
- Not updating diameter correctly
- Ignoring parent to avoid cycles
int diameter = 0;
int dfs(int node, int parent, vector<int> adj[]) {
int max1 = 0, max2 = 0;
for (int child : adj[node]) {
int height = dfs(child, node, adj) + 1;
if (height > max1) {
max2 = max1;
max1 = height;
} else if (height > max2) {
max2 = height;
}
}
diameter = max(diameter, max1 + max2);
return max1;
}
// Called with dfs(1, -1, adj);Solution
Step 1: Identify missing parent check in DFS loop
The code does not skip the parent node, causing infinite recursion or wrong heights.Step 2: Explain impact of missing check
Without skipping parent, DFS revisits parent, causing incorrect diameter calculation or stack overflow.Final Answer:
Missing check to skip parent node in DFS -> Option CQuick Check:
Skip parent to avoid cycles [OK]
- Forgetting to skip parent node
- Returning wrong height value
- Incorrect diameter initialization
Solution
Step 1: Incorporate edge weights in DFS height calculation
Instead of adding 1 for each edge, add the actual edge weight to the height returned by DFS.Step 2: Update diameter with sum of two largest weighted heights
Keep track of two largest weighted heights from children and update diameter with their sum.Final Answer:
Add edge weights to height calculations and update diameter with weighted sums -> Option AQuick Check:
Weighted diameter sums edge weights [OK]
- Ignoring weights in diameter calculation
- Multiplying weights instead of adding
- Using unweighted BFS for weighted tree
Ready to prove it?
Pass the test and this pattern moves unknown
