【二叉树】hdu 1710 Binary Tree Traversals

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+2;
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-1,x+1,mp[pre[x+1]]);
    nd->rig=dfs(y+1,r,x+y-l+1,mp[pre[x+y-l+1]]);
    return nd;
}
void postorder(node *root){
    if(root==NULL) return;
    postorder(root->lef);
    postorder(root->rig);
    if(root->id==pre[0]){
        printf("%d\n",root->id);
    }else{
        printf("%d ",root->id);
    }
    free(root);
}
int main(){
    while(~scanf("%d",&n)){
        for(int i=0;i<n;i++){
            scanf("%d",&pre[i]);
        }
        for(int i=0;i<n;i++){
            scanf("%d",&in[i]);
            mp[in[i]]=i;
        }
        if(n==1) {
            printf("1\n");
            continue;
        } 
        node *root=dfs(0,n-1,0,mp[pre[0]]);
        postorder(root);
    }
    return 0;
} 
View Code

猜你喜欢

转载自www.cnblogs.com/itcsl/p/9175547.html