pat 1020 tree travel

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
#include <cstdio>
#include <queue>
#define MAX 30
#define NULL 0
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int N ;//节点数目
int in[MAX] , post[MAX];
node* create(int postL , int postR , int inL , int inR)
{
if(postL > postR)
return NULL;
node* root = new node;
root->data = post[postR];
int k;
for(k = inL ; k <= inR ; ++k)
{
if(in[k] == post[postR])
break;
}
int numLeft = k - inL;
root->lchild = create(postL , postL + numLeft-1 , inL , k-1);
root->rchild = create(postL+numLeft, postR-1 , k+1 , inR);
return root;
}
void layerOrder(node* root)
{
queue<node*> q;
q.push(root);
printf("%d" , root->data);
bool flag = true;
while(!q.empty())
{
node* now = q.front();
q.pop();
if(!flag)
printf(" %d" , now->data);
if(now->lchild)
q.push(now->lchild);
if(now->rchild)
q.push(now->rchild);
flag = false;
}
}
int main()
{
node* root;
scanf("%d" , &N);
int i;
for(i = 0 ; i < N ; ++i)
scanf("%d" , &post[i]);
for(i = 0 ; i < N ; ++i)
scanf("%d" , &in[i]);
root = create(0 , N-1, 0 , N-1);
//preOrder(root);
layerOrder(root);
return 0;
}

热评文章