-
Notifications
You must be signed in to change notification settings - Fork 0
/
height.cpp
64 lines (59 loc) · 1.08 KB
/
height.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Node
{
public:
int data;
vector<Node *> children;
Node(int data)
{
this->data = data;
}
};
Node *input()
{
stack<Node *> *stk = new stack<Node *>;
int element, root_data, size;
cin >> size >> root_data;
Node *root = new Node(root_data);
stk->push(root);
while (!stk->empty())
{
cin >> element;
if (element == -1)
{
stk->pop();
}
else
{
Node *new_node = new Node(element);
stk->top()->children.push_back(new_node);
stk->push(new_node);
}
}
return root;
}
int height(Node *root)
{
if (root == NULL)
{
return -1;
}
if (root->children.size() == 0)
{
return 0;
}
int sub_height = -1;
for (int i = 0; i < root->children.size(); i++)
{
sub_height = max(sub_height, height(root->children[i]));
}
return 1 + sub_height;
}
int main()
{
Node *root = input();
cout << height(root) << '\n';
}