1020. Tree Traversals (25)

题目连接:https://www.patest.cn/contests/pat-a-practise/1020

原题如下:

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
这道题是要求利用中序和后序写出层序。不用建树即可,利用递归。我写的还是有些繁琐了,主要是中间那块不太确定,求稳了些……
大致的思路就是先在后序中找到根,存入数组中,然后递归的解决左右两边,递归终止条件是参数中左边的序列大于右边。
代码如下:
 1 #include<stdio.h>
 2 #define MAXN 65535
 3 int lastnum=0,N,PostOrder[MAXN],InOrder[MAXN];
 4 int LevelOrder[MAXN]={0};
 5 
 6 void Find(int Istart,int Iend,int Pstart,int Pend,int num)
 7 {
 8     if (Iend<Istart||Pend<Pstart)return ;
 9     else
10     {
11         LevelOrder[num]=PostOrder[Pend];
12        // printf("%d ",PostOrder[Pend]);
13         if (num>lastnum)lastnum=num;
14         int i;
15         for (i=Istart;i<=Iend;i++)
16         {
17             if (InOrder[i]==PostOrder[Pend])break;
18         }
19         int center,Lchild,Rchild;
20         int LengthLeft,LengthRight;
21         int LeftEnd,RightEnd;
22 
23         center=i;
24 
25         LengthLeft=center-Istart;  //中序中的左边长度
26         LengthRight=Iend-center;   //中序中的右边长度
27 
28         Lchild=num*2+1;  //左子树序号
29         Rchild=num*2+2;  //右子树序号
30 
31         LeftEnd=Pstart+LengthLeft-1;  //后序中左半边的最右边界
32         RightEnd=LeftEnd+LengthRight; //后序中右半边的最右边界
33 
34         Find(Istart,center-1,Pstart,LeftEnd,Lchild);
35         Find(center+1,Iend,LeftEnd+1,RightEnd,Rchild);
36 
37     }
38 }
39 int main()
40 {
41     int i;
42     scanf("%d",&N);
43     for (i=0;i<N;i++)scanf("%d",&PostOrder[i]);
44     for (i=0;i<N;i++)scanf("%d",&InOrder[i]);
45 
46     Find(0,N-1,0,N-1,0);
47 
48     //printf("%d\n",lastnum);
49     int flag=0;
50     for (i=0;i<=lastnum;i++)
51     {
52         if (LevelOrder[i]!=0)
53         {
54            // printf("%d ",i);
55             if (flag==0){printf("%d",LevelOrder[i]);flag=1;}
56            else printf(" %d",LevelOrder[i]);
57         }
58     }
59 
60     return 0;
61 }

 


posted @ 2017-02-02 22:05  变通无敌  阅读(139)  评论(0编辑  收藏  举报