劍指offer 06:重建二叉樹

#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <exception>

using namespace std;

#define PB push_back
#define MP make_pair
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,l,h) for(int i=(l);i<=(h);++i)
#define DWN(i,h,l) for(int i=(h);i>=(l);--i)
#define CLR(vis,pos) memset(vis,pos,sizeof(vis))
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LINF 1000000000000000000LL
#define eps 1e-8

typedef long long ll;

struct BTnode{
    int val;
    BTnode *lchild;
    BTnode *rchild;
};

bool flag;

BTnode *construct_core(int *start_preorder,int *end_preorder,int *start_inorder,int *end_inorder){
    int root_val=*start_preorder;
    BTnode *root=new BTnode;
    root->val=root_val;
    root->lchild=root->rchild=NULL;
    if(start_preorder==end_preorder){
        if(start_inorder==end_inorder && *start_preorder==*start_inorder)
            return root;
        else{
            flag=false;
            return NULL;
        }
    }

    int *root_inorder=start_inorder;
    while(root_inorder<=end_inorder && *root_inorder!=root_val)
        root_inorder++;
    if(root_inorder==end_inorder && *root_inorder!=root_val){
        flag=false;
        return NULL;
    }
    int left_len=root_inorder-start_inorder;
    int *left_preorder_end=start_preorder+left_len;
    if(left_len>0){
        root->lchild=construct_core(start_preorder+1,left_preorder_end,start_inorder,root_inorder-1);
    }
    if(left_len<end_preorder-start_preorder){
        root->rchild=construct_core(left_preorder_end+1,end_preorder,root_inorder+1,end_inorder);
    }
    return root;
}

BTnode *construct(int *preorder,int *inorder,int len){
    if(preorder==NULL || inorder==NULL || len<=0)
        return NULL;
    return construct_core(preorder,preorder+len-1,inorder,inorder+len-1);
}

void post_order(BTnode *root){
    if(root!=NULL){
        post_order(root->lchild);
        post_order(root->rchild);
        printf("%d ",root->val);
    }
}

int main()
{
    int n;
    int a[1111],b[1111];
    while(cin>>n){
        CLR(a,0),CLR(b,0);
        flag=true;
        REP(i,n)
          scanf("%d",&a[i]);
        REP(i,n)
          scanf("%d",&b[i]);
        BTnode *root=construct(a,b,n);
        if(flag){
            post_order(root);
            printf("\n");
        }
        else
            printf("No\n");
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章