二叉树的 先序+中序=后序,后序+中序=先序

来源:互联网 发布:推荐几家女装淘宝店铺 编辑:程序博客网 时间:2024/06/15 20:06
#include<iostream>  using namespace std;  typedef int ElemType;struct BTNode{ElemType data;BTNode * lchild;BTNode * rchild;};//先序+中序=建树 BTNode *  PreInCreate(ElemType pre[],ElemType in[],int len){if(pre==NULL || in==NULL || len<=0) return NULL;int i=0;BTNode * T=new BTNode;T->lchild=T->rchild=NULL;int leftlen,rightlen;ElemType tmp=pre[0];T->data=tmp;while(i<len){if(in[i]!=tmp) i++;else   break;}leftlen=i;rightlen=len-i-1;if(leftlen>0) T->lchild=PreInCreate(pre+1,in,leftlen);if(rightlen>0) T->rchild=PreInCreate(pre+leftlen+1,in+leftlen+1,rightlen);return T;}//后序+中序=建树 BTNode *  PostInCreate(ElemType post[],ElemType in[],int len){if(post==NULL || in==NULL || len<=0) return NULL;int i=0;BTNode * T=new BTNode;T->lchild=T->rchild=NULL;int leftlen,rightlen;ElemType tmp=post[len-1];T->data=tmp;while(i<len){if(in[i]!=tmp) i++;else   break;}leftlen=i;rightlen=len-i-1;if(leftlen>0) T->lchild=PostInCreate(post,in,leftlen);if(rightlen>0) T->rchild=PostInCreate(post+leftlen,in+leftlen+1,rightlen);return T;}//先序遍历   void PreOrder(BTNode * T){      //这步判断一定要有,处理建树时的return NULL       if(T){                      cout<<T->data;          PreOrder(T->lchild);          PreOrder(T->rchild);           }     } //后序遍历  void PostOrder(BTNode * T){      //这步判断一定要有,处理建树时的return NULL       if(T){          PostOrder(T->lchild);          PostOrder(T->rchild);              cout<<T->data;       }   }    int  main(){  int a[6]={1,2,3,4,5,6},b[6]={3,2,4,1,6,5},c[6]={3,4,2,6,5,1};BTNode * T1,* T2;T1=PreInCreate(a,b,6);cout<<"先序+中序建树,后序遍历的结果为:"; PostOrder(T1); cout<<endl;T2=PostInCreate(c,b,6);cout<<"后序+中序建树,先序遍历的结果为:"; PreOrder(T2);  cout<<endl;return 0;  }  

1 0
原创粉丝点击