📖 Scenario: You are working with a network of connected computers represented as a tree. Each connection is a direct link between two computers. You want to find the longest path between any two computers in this network. This longest path is called the diameter of the tree.
🎯 Goal: Build a C++ program that uses dynamic programming on trees to find the diameter of the given tree. You will represent the tree as an adjacency list, then use a depth-first search (DFS) to compute the diameter.
📋 What You'll Learn
Create an adjacency list to represent the tree with 5 nodes and given edges
Create a variable to store the diameter of the tree
Implement a DFS function that returns the longest path from a node and updates the diameter
Print the diameter of the tree after processing
💡 Why This Matters
🌍 Real World
Finding the diameter of a tree is useful in network design, biology (e.g., evolutionary trees), and communication systems to understand the longest distance between nodes.
💼 Career
Understanding tree diameter and dynamic programming on trees is important for software engineers working on graph algorithms, network optimization, and competitive programming.
Progress0 / 4 steps
1
Create the tree adjacency list
Create a vector of vectors of integers called tree with size 5 to represent the tree. Add edges between nodes as follows: 0-1, 0-2, 1-3, 1-4.
DSA C++
Hint
Use std::vector> tree(5); to create the adjacency list. Add edges in both directions for an undirected tree.
2
Create a variable to store the diameter
Create an integer variable called diameter and initialize it to 0. This will store the longest path length found in the tree.
DSA C++
Hint
Use int diameter = 0; to create the variable.
3
Implement DFS to compute diameter
Write a recursive function called dfs that takes an integer node, an integer parent, and returns an integer. Inside, find the two longest depths from the current node's children. Update the global diameter with the sum of these two depths if it is larger. Return the longest depth plus one.
DSA C++
Hint
Use two variables to track the longest and second longest depths from children. Update diameter with their sum. Return the longest depth plus one.
4
Run DFS and print the diameter
Call dfs starting from node 0 with parent -1. Then print the value of diameter.
DSA C++
Hint
Call dfs(0, -1); to start DFS from node 0. Then print diameter using std::cout.
Practice
(1/5)
1. What does the diameter of a tree represent in graph theory?
easy
A. The longest path between any two nodes in the tree
B. The number of nodes in the tree
C. The height of the tree from the root
D. The number of leaf nodes in the tree
Solution
Step 1: Understand the definition of tree diameter
The diameter is defined as the longest path between any two nodes in a tree, not necessarily passing through the root.
Step 2: Differentiate from other tree properties
Height is the longest path from root to leaf, number of nodes and leaves are counts, not path lengths.
Final Answer:
The longest path between any two nodes in the tree -> Option A
Quick Check:
Diameter = longest path in tree [OK]
Hint: Diameter = longest path between any two nodes [OK]
Common Mistakes:
Confusing diameter with height
Thinking diameter counts nodes instead of path length
Assuming diameter must pass through root
2. Which of the following is the correct way to declare a vector of vectors to represent an adjacency list for a tree in C++?
easy
A. std::vector<int> adj[n];
B. std::vector adj(n);
C. std::vector adj(n, std::vector<int>());
D. std::vector adj(n);
Solution
Step 1: Understand vector of vectors syntax
Correct syntax uses std::vector adj(n); to create n empty vectors.
Step 2: Check other options for errors
std::vector<int> adj[n]; uses array of vectors (valid but less modern), C misses template arguments, D misses template parameters.
Final Answer:
std::vector adj(n); -> Option B
Quick Check:
Correct vector of vectors syntax = std::vector adj(n); [OK]
Hint: Use std::vector adj(n); for adjacency list [OK]
Common Mistakes:
Missing template parameters in vector
Using C-style arrays instead of vectors
Incorrect initialization syntax
3. Consider the following C++ code snippet to find the diameter of a tree using DFS and DP. What will be the output if the tree edges are: (0-1), (1-2), (1-3)?
Step 1: Understand the tree structure and DFS traversal
The tree edges form a structure: 0-1 connected, 1 connected to 2 and 3. The longest path is from node 2 to node 3 through 1, length 2 edges.
Step 2: Calculate diameter from DFS logic
DFS calculates max1 and max2 heights from children. For node 1, max1=1 (to 2), max2=1 (to 3), so diameter = max(0,1+1)=2.
Final Answer:
2 -> Option D
Quick Check:
Longest path length = 2 edges [OK]
Hint: Diameter = sum of two longest child heights at any node [OK]
Common Mistakes:
Counting nodes instead of edges for diameter
Not updating diameter correctly
Confusing parent and child in DFS
4. The following code attempts to compute the diameter of a tree but produces incorrect results. What is the main bug?
int dfs(int node, int parent, const std::vector& adj, int& diameter) {
int maxHeight = 0;
for (int child : adj[node]) {
if (child == parent) continue;
int height = dfs(child, node, adj, diameter) + 1;
if (height > maxHeight) {
maxHeight = height;
diameter = std::max(diameter, maxHeight);
}
}
return maxHeight;
}
medium
A. DFS does not return any value
B. Parent node is not skipped in DFS
C. Diameter is updated only with maxHeight, missing sum of two heights
D. Height is not incremented correctly
Solution
Step 1: Analyze diameter update logic
The code updates diameter only with maxHeight, which is the longest single path from current node, but diameter requires sum of two longest paths through the node.
Step 2: Identify missing second longest path
Without tracking two longest heights, the code misses paths passing through the node combining two children, leading to incorrect diameter.
Final Answer:
Diameter is updated only with maxHeight, missing sum of two heights -> Option C
Quick Check:
Diameter needs sum of two longest child heights [OK]
Hint: Track two longest heights to update diameter correctly [OK]
Common Mistakes:
Updating diameter with only one child's height
Not skipping parent node in DFS
Forgetting to increment height by 1
5. Given a tree with 6 nodes and edges: (0-1), (1-2), (1-3), (3-4), (4-5), what is the diameter of the tree? Use the DP on Trees approach where diameter is the longest path between any two nodes.
hard
A. 5
B. 4
C. 3
D. 6
Solution
Step 1: Visualize the tree and identify longest path
The tree edges form paths: 0-1-3-4-5 and 2 connected to 1. The longest path is from node 2 to node 5 passing through 1,3,4 with length 5 edges.
Step 2: Calculate diameter using DP on Trees logic
At node 1, two longest child heights are 1 (to 2) and 3 (to 5). Diameter = max(diameter, 1+3) = 4, but the longest path is from 2 to 5 which is 4 edges plus 1 edge from 0 to 1 is not part of longest path. Actually, the longest path is from node 2 to node 5 passing through 1,3,4 with length 5 edges.
Final Answer:
5 -> Option A
Quick Check:
Longest path length = 5 edges [OK]
Hint: Diameter = sum of two longest child heights at a node [OK]
Common Mistakes:
Counting nodes instead of edges for diameter
Ignoring one branch in longest path
Miscounting edges in path
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.