利用先序中序构造二叉树代码实现

#include<bits/stdc++.h>
using namespace std;
typedef struct bitnode{
	char e;
	struct bitnode *lchild,*rchild;
		
}bitnode;

int locate(char c,char *s){
	for(int i=0;i<strlen(s);i++){
		if(c==s[i]){
			return i;
		}
	}
}

void preordertravse(bitnode *t1){
	if(t1!=NULL){
		cout<<t1->e<<endl;
		preordertravse(t1->lchild);
		preordertravse(t1->rchild);
	}
}

void inordertravse(bitnode *t1){
	if(t1!=NULL){
		inordertravse(t1->lchild);
		cout<<t1->e<<endl;
		inordertravse(t1->rchild);
	}
}

void postordertravse(bitnode *t1){
	if(t1!=NULL){
		postordertravse(t1->lchild);
		postordertravse(t1->rchild);
		cout<<t1->e<<endl;
	}
}

bitnode* creatbitree(char *prestring,char *instring,int startp,int endp,int starti,int endi){
		bitnode *root=(bitnode*)malloc(sizeof(bitnode));
		root->e=prestring[startp];
		int position=locate(root->e,instring);
		int lenl=position-starti;
		int lenr=endi-position;
		if(lenl)
			root->lchild=creatbitree(prestring,instring,startp+1,startp+lenl,starti,starti+lenl-1);	
		else
			root->lchild=NULL;
		if(lenr)
			root->rchild=creatbitree(prestring,instring,endp-lenr+1,endp,endi-lenr+1,endi);
		else 
			root->rchild=NULL;
		return root;
}

int main(){
	int count=0;
	char *pres="abecdfghij";
	char *ines="ebcdafhigj";
	bitnode *tree;
	tree=creatbitree(pres,ines,0,9,0,9);
	preordertravse(tree);
	cout<<endl;
	inordertravse(tree);
	cout<<endl;
	postordertravse(tree);
}

 运行结果:

分别是建好树之后再先序中序后序输出:

欢迎参考学习;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值