forked from rudi8848/data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.2.height.cpp
More file actions
102 lines (86 loc) · 1.5 KB
/
1.2.height.cpp
File metadata and controls
102 lines (86 loc) · 1.5 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <vector>
#include <algorithm>
struct Node
{
int data;
struct Node *parent;
std::vector <struct Node*> ch;
};
int Height(struct Node *root)
{
int height = 1;
for (auto c : root->ch)
height = std::max(height, 1 + Height(c));
return height;
}
struct Node *FindRoot(std::vector<int> &list)
{
struct Node *root = new struct Node;
root->parent = NULL;
root->data = -1;
for (int i = 0; i < list.size(); ++i)
{
if (list[i] == -1)
{
root->data = i;
break;
}
}
if (root->data < 0)
{
delete root;
return NULL;
}
return root;
}
void FindChildren(std::vector<int> &list, struct Node *root)
{
for (int i = 0; i < list.size(); ++i)
{
if (list[i] == root->data)
{
struct Node *child = new struct Node;
child->parent = root;
child->data = i;
FindChildren(list, child);
root->ch.push_back(child);
}
}
}
struct Node *BuiltTree(std::vector<int> &tree)
{
struct Node *root = FindRoot(tree);
if (!root)
return NULL;
FindChildren(tree, root);
return root;
}
void PrintTree(struct Node *root)
{
std::cout << root->data << std::endl;
for (auto c : root->ch)
PrintTree(c);
}
int main(void)
{
int n = 0;
std::cin >> n ;
if (n < 1)
return 0;
else if (n == 1)
{
std::cout << n << std::endl;
return 0;
}
std::vector<int> v(n);
for (int i = 0; i < v.size(); ++i)
std::cin >> v[i];
struct Node *root = BuiltTree(v);
//PrintTree(root);
if (root)
std::cout << Height(root) << std::endl;
else
std::cout << 0 << std::endl;
return 0;
}