You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#include<iostream>
#include<vector>// global declarations// MAX is the maximum limit for the number of nodes (100,000).constint MAX = 1e5;
// adjacency list
std::vector<int> adj[MAX];
std::vector<bool> visited;
std::vector<int> dp;
voiddepth_first_search(int u) {
visited[u] = true;
int child_height = 1;
for (int v : adj[u]) {
if (!visited[v]) {
depth_first_search(v);
// select maximum sub-tree height from all children.
child_height = std::max(child_height, dp[v] + 1);
}
}
// assigned the max child height to current visited node.
dp[u] = child_height;
}
intmain() {
// number of nodesint number_of_nodes;
std::cout << "Enter number of nodes of the tree : " << std::endl;
std::cin >> number_of_nodes;
// u, v denotes an undirected edge of tree.int u, v;
// Tree contains exactly n-1 edges where n denotes the number of nodes.
std::cout << "Enter edges of the tree : " << std::endl;
for (int i = 0; i < number_of_nodes - 1; i++) {
std::cin >> u >> v;
// undirected tree u -> v and v -> u.
adj[u].push_back(v);
adj[v].push_back(u);
}
// initialize all nodes as unvisited.
visited.assign(number_of_nodes + 1, false);
// initialize depth of all nodes to 0.
dp.assign(number_of_nodes + 1, 0);
// function call which will initialize the height of all nodes.depth_first_search(1);
std::cout << "Height of the Tree : " << dp[1] << std::endl;
}
DFS Function:
depth_first_search(int u) is a recursive function to perform DFS starting from node u.
Marks node u as visited.
Initializes child_height to 1, representing the height of a single node.
Iterates over all adjacent nodes v of u. If v is not visited, it recursively calls depth_first_search(v).
Updates child_height to the maximum height found among all child nodes plus one (for the current node).
Assigns the calculated child_height to dp[u], representing the height of the subtree rooted at node u.