TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
tree_height.cpp
1// C++ Program to find height of the tree using bottom-up dynamic programming.
2
3/*
4 * Given a rooted tree with node 1.
5 * Task is to find the height of the tree.
6 * Example: -
7 * 4
8 * 1 2
9 * 1 3
10 * 2 4
11 * which can be represented as
12 * 1
13 * / \
14 * 2 3
15 * |
16 * 4
17 *
18 * Height of the tree : - 2
19 */
20
21#include <iostream>
22#include <vector>
23
24// global declarations
25// no of nodes max limit.
26const int MAX = 1e5;
27// adjacency list
28std::vector<int> adj[MAX];
29std::vector<bool> visited;
30std::vector<int> dp;
31
32void depth_first_search(int u) {
33 visited[u] = true;
34 int child_height = 1;
35 for (int v : adj[u]) {
36 if (!visited[v]) {
38
39 // select maximum sub-tree height from all children.
40 child_height = std::max(child_height, dp[v] + 1);
41 }
42 }
43 // assigned the max child height to current visited node.
44 dp[u] = child_height;
45}
46
47int main() {
48 // number of nodes
49 int number_of_nodes;
50 std::cout << "Enter number of nodes of the tree : " << std::endl;
51 std::cin >> number_of_nodes;
52
53 // u, v denotes an undirected edge of tree.
54 int u, v;
55 // Tree contains exactly n-1 edges where n denotes the number of nodes.
56 std::cout << "Enter edges of the tree : " << std::endl;
57 for (int i = 0; i < number_of_nodes - 1; i++) {
58 std::cin >> u >> v;
59 // undirected tree u -> v and v -> u.
60 adj[u].push_back(v);
61 adj[v].push_back(u);
62 }
63 // initialize all nodes as unvisited.
64 visited.assign(number_of_nodes + 1, false);
65 // initialize depth of all nodes to 0.
66 dp.assign(number_of_nodes + 1, 0);
67 // function call which will initialize the height of all nodes.
69 std::cout << "Height of the Tree : " << dp[1] << std::endl;
70}
int main()
Main function.
Functions for Depth First Search algorithm.
for std::vector