-
Notifications
You must be signed in to change notification settings - Fork 2
/
A1020.cpp
62 lines (57 loc) · 1.17 KB
/
A1020.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
#include <cstdio>
#include <queue>
using namespace std;
const int MAXN = 40;
int post[MAXN], in[MAXN];
struct Node{
int key;
Node *lchild, *rchild;
};
Node *newNode(int key){
Node *node = new Node;
node->key = key;
node->lchild = node->rchild = NULL;
return node;
}
Node *buildTree(int postL, int postR, int inL, int inR){
if(postL > postR) return NULL;
Node *root = newNode(post[postR]);
int k;
for(k = inL; k <= inR; ++k){
if(post[postR] == in[k]) break;
}
int numLeft = k - inL;
root->lchild = buildTree(postL, postL+numLeft-1, inL, k-1);
root->rchild = buildTree(postL+numLeft, postR-1, k+1, inR);
return root;
}
void levelOrder(Node *root){
int first = true;
queue<Node *> q;
q.push(root);
while(!q.empty()){
Node *node = q.front();
q.pop();
if(first == false){
printf(" ");
}else{
first = false;
}
printf("%d", node->key);
if(node->lchild != NULL) q.push(node->lchild);
if(node->rchild != NULL) q.push(node->rchild);
}
}
int main(){
int N;
scanf("%d", &N);
for(int i = 0; i < N; ++i){
scanf("%d", &post[i]);
}
for(int i = 0; i < N; ++i){
scanf("%d", &in[i]);
}
Node *root = buildTree(0, N-1, 0, N-1);
levelOrder(root);
return 0;
}