0
0
DSA Cprogramming~30 mins

DP on Trees Diameter of Tree in DSA C - Build from Scratch

Choose your learning style9 modes available
DP on Trees: Diameter of Tree
📖 Scenario: You are working on a network of computers connected by cables. The network forms a tree structure where each computer is a node, and cables are edges. 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 program in C that uses dynamic programming on trees to find the diameter of a given tree. You will represent the tree using adjacency lists, compute the diameter using a depth-first search (DFS) with DP, and print the diameter length.
📋 What You'll Learn
Create an adjacency list to represent the tree with 5 nodes and given edges
Create a global variable to store the maximum diameter found
Write a DFS function that returns the longest path from a node down to its descendants and updates the diameter
Print the diameter of the tree after DFS traversal
💡 Why This Matters
🌍 Real World
Finding the diameter of a tree is useful in network design, biology (evolution trees), and communication systems to understand the longest delay or distance between nodes.
💼 Career
Understanding tree diameters 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 an adjacency list called adj for a tree with 5 nodes (numbered 0 to 4). Add edges: 0-1, 0-2, 1-3, 1-4. Use an array of vectors or arrays to store neighbors.
DSA C
Hint

Use two arrays: adj to store neighbors and adj_size to track number of neighbors for each node. Add edges in both directions.

2
Create a global variable for diameter
Add a global integer variable called diameter and initialize it to 0. This will store the maximum diameter found during DFS.
DSA C
Hint

Declare diameter outside main so it is global and accessible in other functions.

3
Write DFS function to compute diameter
Write a function int dfs(int node, int parent) that returns the longest path from node down to its descendants. Inside, find the top two longest child paths, update the global diameter with their sum if larger, and return the longest child path plus one.
DSA C
Hint

Use two variables max1 and max2 to track the longest and second longest child paths. Update diameter with their sum. Return max1 + 1 for the current node's longest path.

4
Print the diameter of the tree
Add a printf statement in main to print the value of diameter after calling dfs(0, -1). The output should be the diameter number.
DSA C
Hint

Call printf("%d\n", diameter); after DFS to print the diameter.