[树的遍历]树的遍历(PTA)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

4 1 6 3 5 7 2

思路:

已知:后序遍历和中序遍历
画树的方法:
第一步:根据后序遍历的特点,我们知道后序遍历最后一个节点即为根节点,即根节点4

代码如下:

 1 #include <iostream>
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 const int maxn = 35;
 5 int hx[maxn],zx[maxn];
 6 int n;
 7 struct node
 8 {
 9     int l,r;
10 };
11 node pp[maxn];
12 int build(int la,int ra,int lb,int rb)
13 {
14     if(lb>rb)
15         return 0;
16     int root,pos1,pos2;
17     root=hx[ra];
18     pos1=lb;
19     while(zx[pos1]!=root)
20         pos1++;
21     pos2=pos1-lb;
22     pp[root].l=build(la,la+pos2-1,lb,pos1-1);
23     pp[root].r=build(la+pos2,ra-1,pos1+1,rb);
24     return root;
25 }
26 void bfs()
27 {
28     queue<int> q;
29     q.push(hx[n]);
30     printf("%d",hx[n]);
31     while(!q.empty())
32     {
33         int now=q.front();
34         q.pop();
35         if(now!=hx[n])
36             printf(" %d",now);
37         if(pp[now].l)
38             q.push(pp[now].l);
39         if(pp[now].r)
40             q.push(pp[now].r);
41     }
42     printf("\n");
43 }
44 int main()
45 {
46     scanf("%d",&n);
47     for(register int i=1;i<=n;i++)
48         scanf("%d",&hx[i]);
49     for(register int i=1;i<=n;i++)
50         scanf("%d",&zx[i]);
51     build(1,n,1,n);
52     bfs();
53     //cout << "Hello world!" << endl;
54     return 0;
55 }
View Code

 

 
 
posted @ 2019-03-22 17:30  听风不成泣  阅读(1317)  评论(3编辑  收藏  举报