TheAlgorithms-C-Plus-Plus/dynamic_programming/tree_height.cpp

76 lines
1.8 KiB
C++
Raw Normal View History

2020-04-21 02:31:48 +08:00
// C++ Program to find height of the tree using bottom-up dynamic programming.
2020-04-18 02:11:59 +08:00
/*
* Given a rooted tree with node 1.
* Task is to find the height of the tree.
2020-04-18 02:03:28 +08:00
* Example: -
* 4
* 1 2
* 1 3
* 2 4
* which can be represented as
* 1
* / \
* 2 3
* |
* 4
*
2020-04-21 02:31:48 +08:00
* Height of the tree : - 2
*/
#include <iostream>
#include <vector>
2020-04-18 02:11:59 +08:00
// global declarations
// no of nodes max limit.
const int MAX = 1e5;
2020-04-18 02:11:59 +08:00
// adjacency list
std::vector<int> adj[MAX];
std::vector<bool> visited;
std::vector<int> dp;
void depth_first_search(int u)
{
visited[u] = true;
int child_height = 1;
for (int v : adj[u])
{
if (!visited[v])
{
2020-04-20 19:34:32 +08:00
depth_first_search(v);
// select maximum sub-tree height from all children.
child_height = std::max(child_height, dp[v] + 1);
}
}
2020-04-18 02:11:59 +08:00
// assigned the max child height to current visited node.
dp[u] = child_height;
}
int main()
{
2020-04-18 02:11:59 +08:00
// number of nodes
2020-04-21 02:37:57 +08:00
int number_of_nodes;
2020-04-20 19:34:32 +08:00
std::cout << "Enter number of nodes of the tree : " << std::endl;
2020-04-21 02:37:57 +08:00
std::cin >> number_of_nodes;
2020-04-21 02:34:04 +08:00
2020-04-21 02:37:57 +08:00
// u, v denotes an undirected edge of tree.
2020-04-18 02:03:28 +08:00
int u, v;
2020-04-21 02:37:57 +08:00
// Tree contains exactly n-1 edges where n denotes the number of nodes.
2020-04-20 19:34:32 +08:00
std::cout << "Enter edges of the tree : " << std::endl;
for (int i = 0; i < number_of_nodes - 1; i++)
{
std::cin >> u >> v;
2020-04-18 02:11:59 +08:00
// undirected tree u -> v and v -> u.
adj[u].push_back(v);
adj[v].push_back(u);
}
2020-04-18 02:11:59 +08:00
// initialize all nodes as unvisited.
visited.assign(number_of_nodes + 1, false);
2020-04-18 02:11:59 +08:00
// initialize depth of all nodes to 0.
dp.assign(number_of_nodes + 1, 0);
2020-04-18 02:11:59 +08:00
// function call which will initialize the height of all nodes.
2020-04-20 19:34:32 +08:00
depth_first_search(1);
2020-04-18 02:03:28 +08:00
std::cout << "Height of the Tree : " << dp[1] << std::endl;
}