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

#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;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值