根據后序和中序遍歷輸出先序遍歷


輸入格式:

第一行給出正整數N(≤),是樹中結點的個數。隨后兩行,每行給出N個整數,分別對應后序遍歷和中序遍歷結果,數字間以空格分隔。題目保證輸入正確對應一棵二叉樹。

輸出格式:

在一行中輸出Preorder:以及該樹的先序遍歷結果。數字間有1個空格,行末不得有多余空格。

輸入樣例:

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

輸出樣例:

Preorder: 4 1 3 2 6 5 7

這題唯一的難點就是如何根據后序和中序遍歷把樹建立起來

先模擬一下 比如后序是2 3 1 5 7 6 4 中序是1 2 3 4 5 6 7
從后序遍歷可以知道4是樹根,6是4的右孩子,然后根據中序遍歷可知1 2 3是4的左子樹,5 6 7 是右子樹 所以1是4的左孩子,這樣依次遞歸下去就可以把樹建好了;
代碼如下:
  
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <set>
 4 #include <vector>
 5 #include <cstring>
 6 #include <algorithm>
 7 using namespace std;
 8 typedef long long ll;
 9 const int maxn=1e5+5;
10 int mid[50],post[50];
11 struct node
12 {
13     int data;
14     node *LNode;
15     node *RNode;
16 };
17 node* build(int *mid,int *post,int n)
18 {
19     if(n<=0)return NULL;
20     int *p=mid;
21     while(p)
22     {
23         if(*p==*(post+n-1))
24             break;
25         p++;
26     }
27     node *T=new node;
28     T->data=*p;
29     int len=p-mid;
30     T->LNode=build(mid,post,len);
31     T->RNode=build(p+1,post+len,n-len-1);
32     return T;
33 }
34 void preprint(node *T)
35 {
36     if(T)
37     {
38         printf(" %d",T->data);
39         preprint(T->LNode);
40         preprint(T->RNode);
41     }
42     return ;
43 }
44 int main()
45 {
46     int n;
47     cin>>n;
48     for(int i=0;i<n;i++)
49         scanf("%d",&post[i]);
50     for(int i=0;i<n;i++)
51         scanf("%d",&mid[i]);
52     node *T;
53     T=build(mid,post,n);
54     printf("Preorder:");
55     preprint(T);
56     printf("\n");
57     return 0;
58 }

 

 


免責聲明!

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



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