« Find height of tree

Find height

Given a generic tree, find and return the height of given tree.

Input Format:

The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.

Output Format :

The first and only line of output prints the height of the given generic tree.

Constraints:

Time Limit: 1 sec

Sample Input 1:

10 3 20 30 40 2 40 50 0 0 0 0

Sample Output 1:

3

1#include <iostream>
2#include <queue>
3#include <vector>
4#include<climits>
5using namespace std;
6
7template <typename T>
8class TreeNode {
9 public:
10 T data;
11 vector<TreeNode<T>*> children;
12
13 TreeNode(T data) { this->data = data; }
14
15 ~TreeNode() {
16 for (int i = 0; i < children.size(); i++) {
17 delete children[i];
18 }
19 }
20};
21
22int getHeight(TreeNode<int>* root) {
23 if(root == NULL){
24 return 0;
25 }
26 int height = 0;
27 for(int i=0; i<root->children.size(); i++){
28 height = max(height, getHeight(root->children[i]));
29 }
30 return (height+1);
31}
32
33TreeNode<int>* takeInputLevelWise() {
34 int rootData;
35 cin >> rootData;
36 TreeNode<int>* root = new TreeNode<int>(rootData);
37
38 queue<TreeNode<int>*> pendingNodes;
39
40 pendingNodes.push(root);
41 while (pendingNodes.size() != 0) {
42 TreeNode<int>* front = pendingNodes.front();
43 pendingNodes.pop();
44 int numChild;
45 cin >> numChild;
46 for (int i = 0; i < numChild; i++) {
47 int childData;
48 cin >> childData;
49 TreeNode<int>* child = new TreeNode<int>(childData);
50 front->children.push_back(child);
51 pendingNodes.push(child);
52 }
53 }
54
55 return root;
56}
57
58int main() {
59 TreeNode<int>* root = takeInputLevelWise();
60 cout << getHeight(root);
61}