Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 590 Accepted Submission(s): 241
本题如果学过数据结构的话,应该问题不大,就是给一个先序遍历,一个中序遍历,求后序遍历,一般我们做的时候就是根据先序遍历和中序遍历建造一个树,然后再对这个树进行后序遍历输出就行了。后序遍历树很简单,我们就不多说了,关键是怎样建树。首先我们应该搞清楚先序遍历和中序遍历,在中序遍历中如果这个数出现在某个节点的前面就表明此数在这个节点的左边,如果这个数出现在某个节点的后面就表明此数出现在这个节点的右边。
代码:
1
#include
<
stdio.h
>
2
#include
<
stdlib.h
>
3
int
n,pre[
1005
],
in
[
1005
];
4
typedef
struct
node
5
{
6
int
data;
7
int
index;
8
struct
node
*
Lchild,
*
Rchild;
9
}bitree,
*
Tree;
10
void
dfs(Tree
&
root,
int
index)
11
{
12
if
(root
==
NULL)
13
{
14
root
=
(Tree)malloc(
sizeof
(bitree));
15
root
->
data
=
in
[index];
16
root
->
index
=
index;
17
root
->
Lchild
=
NULL;
18
root
->
Rchild
=
NULL;
19
return
;
20
}
21
else
22
{
23
if
(index
<
root
->
index)
24
dfs(root
->
Lchild,index);
25
else
26
dfs(root
->
Rchild,index);
27
}
28
}
29
void
createbitree(Tree
&
root)
30
{
31
int
i,j,index;
32
root
=
(Tree)malloc(
sizeof
(bitree));
33
for
(i
=
1
;i
<=
n;i
++
)
34
if
(
in
[i]
==
pre[
1
])
35
{
36
root
->
data
=
pre[
1
];
37
root
->
index
=
i;
38
root
->
Lchild
=
NULL;
39
root
->
Rchild
=
NULL;
40
break
;
41
}
42
index
=
i;
43
for
(i
=
2
;i
<=
n;i
++
)
44
for
(j
=
1
;j
<=
n;j
++
)
45
if
(
in
[j]
==
pre[i])
46
{
47
if
(j
<
index)
48
dfs(root
->
Lchild,j);
49
else
50
dfs(root
->
Rchild,j);
51
break
;
52
}
53
}
54
void
post(Tree root,
int
x)
55
{
56
if
(root
==
NULL)
57
return
;
58
post(root
->
Lchild,x
+
1
);
59
post(root
->
Rchild,x
+
1
);
60
if
(x
==
0
)
61
printf(
"
%d
"
,root
->
data);
62
else
63
printf(
"
%d
"
,root
->
data);
64
}
65
int
main()
66
{
67
int
i;
68
while
(scanf(
"
%d
"
,
&
n)
!=
EOF)
69
{
70
Tree root;
71
for
(i
=
1
;i
<=
n;i
++
)
72
scanf(
"
%d
"
,
&
pre[i]);
73
for
(i
=
1
;i
<=
n;i
++
)
74
scanf(
"
%d
"
,
&
in
[i]);
75
createbitree(root);
76
post(root,
0
);
77
printf(
"
\n
"
);
78
}
79
return
0
;
80
}
81

