HDU 1710 Binary Tree Traversals

时间:2021-10-12 23:49:14

题意:给出一颗二叉树的前序遍历和中序遍历,输出其后续遍历

首先知道中序遍历是左子树根右子树递归遍历的,所以只要找到根节点,就能够拆分出左右子树

前序遍历是按照根左子树右子树递归遍历的,那么可以找出这颗树的根节点,

然后拆分出左右子树,对左右子树进行相同的操作,也就是将建树的这个函数递归调用下去

build函数还是理解了好久啊话说= =仍然是学习的代码

 #include<iostream>
#include<cstdio>
#include<cstring>
#include <cmath>
#include<algorithm>
using namespace std; typedef long long LL;
const int maxn=; void build(int n,int *s1,int *s2,int *s){
if(n<=) return;
int p;
for(int i=;i<n;i++){
if(s2[i]==s1[]){
p=i;//在中序遍历中找到根结点的位置
break;
}
} build(p,s1+,s2,s);//p为左子树的区间长度,s1+1是在前序遍历中左子树的开头,s2是在中序遍历中左子树的开头
build(n-p-,s1+p+,s2+p+,s+p);//n-p-1为右子树的区间长度,s1+p+1 是在前序遍历中右子树的开头,s2是在中序遍历中右子树的开头
s[n-]=s1[];
} int main()
{
int n,i,ans[maxn],s1[maxn],s2[maxn];
while(scanf("%d",&n)!=EOF){
for(i=;i<n;i++) scanf("%d",&s1[i]);
for(i=;i<n;i++) scanf("%d",&s2[i]);
build(n,s1,s2,ans);
for(i=;i<n-;i++) printf("%d ",ans[i]);
printf("%d\n",ans[i]);
}
return ;
}