-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrees_traverse.cpp
More file actions
102 lines (86 loc) · 2.04 KB
/
trees_traverse.cpp
File metadata and controls
102 lines (86 loc) · 2.04 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 <algorithm>
#include <iostream>
#include <vector>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/resource.h>
#endif
using namespace std;
class Node;
class Node {
public:
int key;
Node *parent;
std::vector<Node *> children;
Node() {
this->parent = NULL;
}
void setParent(Node *theParent) {
parent = theParent;
parent->children.push_back(this);
}
};
//my dfs
int res=0;
int dfs (Node * x,int depth){
if (x->children.empty())
return 0;
if (depth>res)
res=depth;
for (int i = 0; i < x->children.size(); i++){
if(x->children[i]!=NULL)
dfs(x->children[i],depth+1);
}
}
int main_with_large_stack_space() {
std::ios_base::sync_with_stdio(0);
int n;
std::cin >> n;
std::vector<Node> nodes;
nodes.resize(n);
for (int child_index = 0; child_index < n; child_index++) {
int parent_index;
std::cin >> parent_index;
if (parent_index >= 0)
nodes[child_index].setParent(&nodes[parent_index]);
nodes[child_index].key = child_index;
}
//my work
vector<Node>search;
for (int i = 0; i < n; i++){
if (nodes[i].children.empty())
search.push_back(nodes[i]);
}
//// Replace this code with a faster implementation
int maxHeight = 0;
for (int leaf_index = 0; leaf_index < search.size(); leaf_index++) {
int height = 0;
for (Node *v = &search[leaf_index]; v != NULL; v = v->parent)
height++;
maxHeight = std::max(maxHeight, height);
}
std::cout << maxHeight << std::endl;
return 0;
}
int main (int argc, char **argv)
{
#if defined(__unix__) || defined(__APPLE__)
// Allow larger stack space
const rlim_t kStackSize = 16 * 1024 * 1024; // min stack size = 16 MB
struct rlimit rl;
int result;
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0)
{
if (rl.rlim_cur < kStackSize)
{
rl.rlim_cur = kStackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0)
{
std::cerr << "setrlimit returned result = " << result << std::endl;
}
}
}
#endif
return main_with_large_stack_space();
}