由先序中序、中序后序构造二叉树

由先序中序、中序后序构造二叉树在这里插入图片描述

#include<iostream>
using namespace std;
# define MaxSize 20
typedef char ElemType;
typedef struct node{
	ElemType data;
	struct node*lchild;
	struct node*rchild;
}BTNode,*BTree ;
void DestroyBTree(BTNode*&b){
	if(b!=NULL){
		DestroyBTree(b->lchild);
		DestroyBTree(b->rchild);
		delete b;
	}
}
void DispBTree(BTNode* b){
	if(b!=NULL){
		cout<<b->data;
		if(b->lchild||b->rchild){
			cout<<"(";
			DispBTree(b->lchild);
			if(b->rchild) cout<<",";
			DispBTree(b->rchild);
			cout<<")";
		}
	}
	
}

void displayBTree(BTNode* T){
BTree stack[100],p;
int level[100],top,n,i;
if(T!=NULL){
top=1;
stack[top]=T;
level[top]=3;
while(top>0){
p=stack[top];
n=level[top];
for(i=1;i<=n;i++)
cout<<" ";
cout<<" "<<p->data<<" ";
//for(i=n+1;i<100-n;i+=2)
//printf("-");
cout<<endl;
top--;
if(p->rchild!=NULL){
top++;
stack[top]=p->rchild;
level[top]=n+3;}
if(p->lchild!=NULL){
top++;
stack[top]=p->lchild;
level[top]=n+3;
}
}
}
}

BTNode*CreateBT1(char*pre,char*in,int n){
	BTNode*b;
	char *p;
	int k;
	if(n<=0) return NULL;
	b= new BTNode;
	b->data=*pre;
	for(p=in;p<in+n;p++)
	if (*p==*pre)
	break;
	k=p-in;
	b->lchild=CreateBT1(pre+1,in,k);
	b->rchild=CreateBT1(pre+1+k,p+1,n-k-1);
	return b;
	
}

BTNode*CreateBT2(char*post,char*in,int n){
	BTNode*b;
	char r,*p;
	int k;
	if(n<=0) return NULL;
	r=*(post+n-1);
	b= new BTNode;
	b->data=r;
	for(p=in;p<in+n;p++)
	if (*p==r)
	break;
	k=p-in;
	b->lchild=CreateBT2(post,in,k);
	b->rchild=CreateBT2(post+k,p+1,n-k-1);
	return b;
	
}

int main(){
	char* pre="ABDEHJKLMNCFGI";
	char* in="DBJHLKMNEAFCGI";
	char* post="DJLNMKHEBFIGCA";
	BTNode* b,*c;
	cout<<"先序遍历 "<<pre<<endl;
	cout<<"中序遍历 "<<in<<endl;
	cout<<"后序遍历 "<<post<<endl;
	cout<<"先序,中序创建子树"<<endl;
    b=CreateBT1(pre,in,14);
    DispBTree(b);
    cout<<endl;
    cout<<"后序,中序创建子树"<<endl;
    c=CreateBT2(post,in,14);
    DispBTree(c);
    cout<<endl;
    displayBTree(b);
    DestroyBTree(b);
    DestroyBTree(c);
}

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值