【二叉树】hdu 1710 Binary Tree Traversals

时间:2022-05-15 00:07:00

acm.hdu.edu.cn/showproblem.php?pid=1710

【题意】

给定一棵二叉树的前序遍历和中序遍历,输出后序遍历

【思路】

根据前序遍历和中序遍历递归建树,再后续遍历输出

malloc申请空间在堆,函数返回,内存不释放,需要free手动释放

【Accepted】

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm> using namespace std;
const int maxn=1e3+;
int n;
int pre[maxn],in[maxn],post[maxn];
int mp[maxn];
struct node{
int id;
node *lef;
node *rig;
node(int i, node *l=NULL, node *r=NULL):id(i),lef(l),rig(r){}
};
node* dfs(int l,int r,int x,int y){
if(l>r) return NULL;
node *nd=(node *)malloc(sizeof(node));
nd->id=in[y];
nd->lef=dfs(l,y-,x+,mp[pre[x+]]);
nd->rig=dfs(y+,r,x+y-l+,mp[pre[x+y-l+]]);
return nd;
}
void postorder(node *root){
if(root==NULL) return;
postorder(root->lef);
postorder(root->rig);
if(root->id==pre[]){
printf("%d\n",root->id);
}else{
printf("%d ",root->id);
}
free(root);
}
int main(){
while(~scanf("%d",&n)){
for(int i=;i<n;i++){
scanf("%d",&pre[i]);
}
for(int i=;i<n;i++){
scanf("%d",&in[i]);
mp[in[i]]=i;
}
if(n==) {
printf("1\n");
continue;
}
node *root=dfs(,n-,,mp[pre[]]);
postorder(root);
}
return ;
}