[樹的遍歷]樹的遍歷(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

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM