Bird
Raised Fist0
DSA Cprogramming~20 mins

DP on Trees Diameter of Tree in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Tree Diameter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of diameter calculation on a simple tree
What is the output of the following C code that calculates the diameter of a tree represented as an adjacency list?
DSA C
#include <stdio.h>
#include <stdlib.h>

#define MAX 5

int adj[MAX][MAX] = {0};
int visited[MAX] = {0};
int max_diameter = 0;

int dfs(int node) {
    visited[node] = 1;
    int max1 = 0, max2 = 0;
    for (int i = 0; i < MAX; i++) {
        if (adj[node][i] && !visited[i]) {
            int dist = dfs(i) + 1;
            if (dist > max1) {
                max2 = max1;
                max1 = dist;
            } else if (dist > max2) {
                max2 = dist;
            }
        }
    }
    if (max1 + max2 > max_diameter) {
        max_diameter = max1 + max2;
    }
    return max1;
}

int main() {
    adj[0][1] = adj[1][0] = 1;
    adj[1][2] = adj[2][1] = 1;
    adj[1][3] = adj[3][1] = 1;
    adj[3][4] = adj[4][3] = 1;

    dfs(0);
    printf("%d\n", max_diameter);
    return 0;
}
A4
B3
C5
D2
Attempts:
2 left
💡 Hint
Think about the longest path between any two nodes in the tree.
🧠 Conceptual
intermediate
1:30remaining
Understanding the diameter calculation logic
In the DP approach to find the diameter of a tree, what does the sum of the two largest depths from a node represent?
AThe height of the tree
BThe total number of nodes in the tree
CThe longest path passing through that node
DThe number of leaf nodes
Attempts:
2 left
💡 Hint
Think about how the diameter can pass through a node connecting two longest branches.
❓ Predict Output
advanced
2:30remaining
Output of diameter calculation with weighted edges
What is the output of the following C code that calculates the diameter of a weighted tree using DP on trees?
DSA C
#include <stdio.h>
#include <stdlib.h>

#define MAX 4

int adj[MAX][MAX] = {0};
int visited[MAX] = {0};
int max_diameter = 0;

int dfs(int node) {
    visited[node] = 1;
    int max1 = 0, max2 = 0;
    for (int i = 0; i < MAX; i++) {
        if (adj[node][i] > 0 && !visited[i]) {
            int dist = dfs(i) + adj[node][i];
            if (dist > max1) {
                max2 = max1;
                max1 = dist;
            } else if (dist > max2) {
                max2 = dist;
            }
        }
    }
    if (max1 + max2 > max_diameter) {
        max_diameter = max1 + max2;
    }
    return max1;
}

int main() {
    adj[0][1] = adj[1][0] = 3;
    adj[1][2] = adj[2][1] = 4;
    adj[1][3] = adj[3][1] = 2;

    dfs(0);
    printf("%d\n", max_diameter);
    return 0;
}
A9
B6
C5
D7
Attempts:
2 left
💡 Hint
Sum the two longest weighted paths from the root node.
🔧 Debug
advanced
2:00remaining
Identify the bug in diameter calculation code
What error will the following code produce when calculating the diameter of a tree?
DSA C
#include <stdio.h>
#include <stdlib.h>

#define MAX 3

int adj[MAX][MAX] = {0};
int visited[MAX] = {0};
int max_diameter = 0;

int dfs(int node) {
    visited[node] = 1;
    int max1 = 0, max2 = 0;
    for (int i = 0; i < MAX; i++) {
        if (adj[node][i] && !visited[i]) {
            int dist = dfs(i) + 1;
            if (dist > max1) {
                max2 = max1;
                max1 = dist;
            } else if (dist > max2) {
                max2 = dist;
            }
        }
    }
    if (max1 + max2 > max_diameter) {
        max_diameter = max1 + max2;
    }
    return max1;
}

int main() {
    adj[0][1] = 1;
    adj[1][0] = 1;
    adj[1][2] = 1;
    // Missing adj[2][1] = 1;

    dfs(0);
    printf("%d\n", max_diameter);
    return 0;
}
AThe diameter will be underestimated due to missing edge
BThe diameter will be overestimated due to double counting
CCompilation error due to missing semicolon
DSegmentation fault due to invalid memory access
Attempts:
2 left
💡 Hint
Check if the tree edges are correctly bidirectional.
🧠 Conceptual
expert
1:30remaining
Why DP on trees is efficient for diameter calculation
Why is the DP approach on trees preferred over brute force for finding the diameter of a tree?
AIt avoids repeated calculations by storing intermediate results, reducing time complexity to O(n)
BIt uses more memory but runs slower than brute force
CIt only works for binary trees, not general trees
DIt requires sorting all nodes which increases complexity
Attempts:
2 left
💡 Hint
Think about how DP avoids repeated work in recursive tree traversal.

Practice

(1/5)
1. What is the diameter of a tree in the context of dynamic programming on trees?
easy
A. The height of the tree from the root
B. The number of nodes in the tree
C. The sum of all edge weights in the tree
D. The longest path between any two nodes in the tree

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The longest path between any two nodes in the tree -> Option D
  4. Quick Check:

    Diameter = Longest path [OK]
Hint: Diameter is longest path between any two nodes [OK]
Common Mistakes:
  • Confusing diameter with height
  • Thinking diameter is number of nodes
  • Assuming diameter is sum of all edges
2. Which of the following is the correct way to declare an adjacency list for a tree with n nodes in C?
easy
A. int adj[n][n];
B. int* adj[n];
C. int adj[n];
D. int adjList[n][2];

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    int* adj[n]; -> Option B
  4. Quick Check:

    Adjacency list uses array of pointers [OK]
Hint: Adjacency list uses array of pointers to neighbors [OK]
Common Mistakes:
  • Using 2D array as adjacency list
  • Using simple array for adjacency
  • Confusing edge list with adjacency list
3. Consider the following C code snippet to find the diameter of a tree. What will be the output if the tree has edges: 1-2, 2-3, 2-4?
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;
medium
A. 2
B. 3
C. 1
D. 4

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Longest path length = 2 edges [OK]
Hint: Diameter = sum of two longest child heights [OK]
Common Mistakes:
  • Counting nodes instead of edges
  • Not updating diameter correctly
  • Ignoring parent to avoid cycles
4. The following code attempts to compute the diameter of a tree but produces incorrect results. What is the bug?
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);
medium
A. Incorrect initialization of diameter variable
B. Returning max2 instead of max1 from DFS
C. Missing check to skip parent node in DFS
D. Not adding 1 to height in DFS call

Solution

  1. Step 1: Identify missing parent check in DFS loop

    The code does not skip the parent node, causing infinite recursion or wrong heights.
  2. Step 2: Explain impact of missing check

    Without skipping parent, DFS revisits parent, causing incorrect diameter calculation or stack overflow.
  3. Final Answer:

    Missing check to skip parent node in DFS -> Option C
  4. Quick Check:

    Skip parent to avoid cycles [OK]
Hint: Always skip parent node in DFS to prevent cycles [OK]
Common Mistakes:
  • Forgetting to skip parent node
  • Returning wrong height value
  • Incorrect diameter initialization
5. Given a weighted tree with edges: (1-2, 3), (2-3, 4), (2-4, 2), how would you modify the diameter calculation to find the longest weighted path? Choose the correct approach.
hard
A. Add edge weights to height calculations and update diameter with weighted sums
B. Ignore weights and use number of edges as diameter
C. Multiply edge weights instead of adding
D. Use BFS twice without considering weights

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Add edge weights to height calculations and update diameter with weighted sums -> Option A
  4. Quick Check:

    Weighted diameter sums edge weights [OK]
Hint: Add weights to heights, sum two largest for diameter [OK]
Common Mistakes:
  • Ignoring weights in diameter calculation
  • Multiplying weights instead of adding
  • Using unweighted BFS for weighted tree
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard