-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathW7_preOrderDepth2.cpp
103 lines (89 loc) · 2.2 KB
/
W7_preOrderDepth2.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
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
// Created by dongwan-kim on 2022/04/12.
#include<iostream>
#include<vector>
using namespace std;
int t,n;
vector<int>nodev;
vector<int>nodedepth;
class Node{
public:
Node* parent;
int value;
vector<Node*> childList;
Node(){
value=0;
parent= nullptr;
}
Node(Node* p,int v){
value=v;
parent=p;
}
};
class Tree{
public:
Node *root;
Tree(){
root=new Node();
}
void postOrderTraversal(Node *r){
for(int i=0;i<r->childList.size();i++){
postOrderTraversal(r->childList[i]);
}
cout<<r->value<<" ";
}
void makeTree(){
int depth=-1;
Node *curNode=root;
for(int i=0;i<n;i++){
if(nodedepth[i]==0){
root->value=1;
depth=nodedepth[i];
curNode=root;
}
else{
if(nodedepth[i]>depth){
Node *newNode=new Node(curNode,nodev[i]);
curNode->childList.push_back(newNode);
curNode=newNode;
}
else if(nodedepth[i]==depth){
Node *newNode=new Node(curNode->parent,nodev[i]);
curNode->parent->childList.push_back(newNode);
curNode=newNode;
}
else if(nodedepth[i]<depth){
while(depth!=nodedepth[i]){
curNode=curNode->parent;
depth--;
}
Node *newNode=new Node(curNode->parent,nodev[i]);
curNode->parent->childList.push_back(newNode);
curNode=newNode;
}
}
depth=nodedepth[i];
}
}
};
int main(){
cin>>t;
while(t--){
nodedepth.clear();
nodev.clear();
Tree tree;
cin>>n;
for(int i=0;i<n;i++){
int a;
cin>>a;
nodev.push_back(a);
}
for(int i=0;i<n;i++){
int a;
cin>>a;
nodedepth.push_back(a);
}
tree.makeTree();
tree.postOrderTraversal(tree.root);
cout<<endl;
}
}