HLG2040二叉树遍历已知前中,求后
| 二叉樹的遍歷 | ||||||
| ||||||
| Description | ||||||
| 給出一棵二叉樹的中序和前序遍歷,輸出它的后序遍歷。 | ||||||
| Input | ||||||
| 本題有多組數據,輸入處理到文件結束。 每組數據的第一行包括一個整數n,表示這棵二叉樹一共有n個節點。 接下來的一行每行包括n個整數,表示這棵樹的中序遍歷。 接下來的一行每行包括n個整數,表示這棵樹的前序遍歷。 3<= n <= 100 | ||||||
| Output | ||||||
| 每組輸出包括一行,表示這棵樹的后序遍歷。 | ||||||
| Sample Input | ||||||
| 7 4 2 5 1 6 3 7 1 2 4 5 3 6 7 ? | ||||||
| Sample Output | ||||||
| 4 5 2 6 7 3 1? | ||||||
| Source | ||||||
| 2014 Winter Holiday Contest 5 |
?
?
?
?
?
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n,num=0;
int kmp(int root,int str2[])
{
??? int s=0;
??? while(1)
??? {
??????? if(str2[s]==root)
??????????? return s;
??????? s++;
??? }
??? return 0;
}
void calculate(int m,int str1[],int str2[],int str3[] )
{
??? if(m<=0)
??????? return ;
??????? int len=kmp(str1[0],str2);
??? calculate(len,str1+1,str2,str3);
??? calculate(m-len-1,str1+len+1,str2+len+1,str3);
??? str3[num++]=str1[0];
}
int main()
{
??????? int n;
??? int str1[105],str2[105],str3[105];
??? while(scanf("%d",&n)!=EOF)
??? {
??????? num=0;
??????? memset(str1,0,sizeof(str1));
??????? memset(str2,0,sizeof(str2));
??????? memset(str3,0,sizeof(str3));
??????? for(int i=0;i<n;i++)
??????????? scanf("%d",&str2[i]);
??????? for(int i=0;i<n;i++)
??????????? scanf("%d",&str1[i]);
??????? calculate(n,str1,str2,str3);
??????? for(int i=0;i<n;i++)
??????????? printf("%d ",str3[i]);
??????????? printf("\n");
??? }
??? return 0;
}
?
轉載于:https://www.cnblogs.com/13224ACMer/p/4428093.html
總結
以上是生活随笔為你收集整理的HLG2040二叉树遍历已知前中,求后的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅谈C++的virtual 动态绑定。
- 下一篇: EMCA和EMCTL的简单用法