剑指offer 06:重建二叉树
2015-03-09 19:22
316 查看
#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; }
相关文章推荐
- 剑指Offer-【面试题06:重建二叉树】
- 剑指Offer_06 根据前序遍历和中序遍历序列 重建二叉树
- 剑指offer面试题06 重建二叉树
- 面试题06_重建二叉树——剑指offer系列
- 剑指offer——重建二叉树
- 剑指Offer面试题6重建二叉树(根据前序中序输出后序)
- 剑指offer面试题java实现之题6:重建二叉树
- 剑指offer-重建二叉树
- 剑指Offer——重建二叉树——C++
- 剑指offer-重建二叉树
- 《剑指offer》根据先序序列与中序序列重建二叉树-Java
- 《剑指Offer》面试题六之重建二叉树
- 剑指offer—重建二叉树
- 06:重建二叉树
- 剑指Offer(四)重建二叉树
- [剑指offer学习心得]之:重建二叉树
- 剑指Offer编程练习__重建二叉树
- 剑指offer编程题——06 重建二叉树
- 《剑指offer》—4、重建二叉树
- 剑指Offer——重建二叉树