-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree_binary_array.cpp
More file actions
131 lines (111 loc) · 2.6 KB
/
Copy pathtree_binary_array.cpp
File metadata and controls
131 lines (111 loc) · 2.6 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
* tree_binary_array
*/
#include <iostream>
#include <vector>
using namespace std;
struct Node {
Node *parent = NULL;
vector<Node *> children = {};
int item;
Node(int a) : item(a), parent(NULL) {}
void insertChild(Node *data) {
children.push_back(data);
}
void setParent(Node *node) {
this->parent = node;
}
};
class Tree {
private:
Node *root = NULL;
vector<Node *> nodeList = {};
int size = 0;
public:
Tree(int a) {
Node *newNode = new Node(a);
root = newNode;
nodeList.push_back(newNode);
size++;
}
void insert(int parent, int data);
void show(int a);
void showDepth(int a);
};
void Tree::insert(int parentData, int data) {
for (int i = 0; i < nodeList.size(); i++) {
Node *parent;
Node *newNode = new Node(data);
if (nodeList[i]->item == parentData) {
parent = nodeList[i];
parent->insertChild(newNode);
newNode->setParent(parent);
nodeList.push_back(newNode);
size++;
break;
}
}
}
void Tree::show(int a) {
for (int i = 0; i < (int) nodeList.size(); i++) {
if (nodeList[i]->item == a) {
if (nodeList[i]->children.size() == 0) {
cout << 0 << endl;
return;
}
for (int j = 0; j < nodeList[i]->children.size(); j++) {
cout << nodeList[i]->children[j]->item << " ";
}
cout << endl;
return;
}
}
}
void Tree::showDepth(int a) {
int depth = 0;
for (int i = 0; i < nodeList.size(); i++) {
if (nodeList[i]->item == a) {
Node *temp = nodeList[i];
while (true) {
if (temp->parent == NULL) {
cout << depth << endl;
return;
} else {
temp = temp->parent;
depth++;
}
}
}
}
}
int main() {
Tree tree(1);
int node, question;
cin >> node >> question;
for (int i = 0; i < node; i++) {
int parent;
cin >> parent;
while (true) {
int a;
cin >> a;
if (a == 0) {
break;
} else {
tree.insert(parent, a);
}
}
}
//for (int i = 0; i < question; i++)
//{
// int c;
// cin >> c;
// tree.show(c);
//}
for (int i = 0; i < question; i++) {
int c;
cin >> c;
tree.showDepth(c);
}
system("pause");
return 0;
}