二叉树的构造

      我们假设二叉树中每个节点的值都不相同,那么二叉树具有唯一的先序序列、中序序列、后序序列(注意不同的二叉树可能有相同的先序、中序、后序序列)。引入如下两个定理(数学归纳法很容易可以证明,这里不给出证明):

1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和先序序列唯一确定。

1.任何n(n≥0)个不同节点的二叉树,都可由它的中序序列和后序序列唯一确定。

给出二叉树的两个序列,返回出二叉树的根结点,代码如下:

/*
Author:Ibsen
Date:2015.12.15
*/
#include <iostream>
using namespace std;
const int M=1000;
typedef struct node
{
	char data;
	struct node *lc,*rc;
}BTree;
BTree* Creat_BTree_pre_in(char *pre,char *in,int n)
{
	BTree *h;
	char *p;
	if(n<=0) return NULL;
	h=new BTree();
	h->data=*pre;
	for(p=in;p<in+n;p++)
		if(*p==*pre) break;
	int pos=p-in;
	h->lc=Creat_BTree_pre_in(pre+1,in,pos);
	h->rc=Creat_BTree_pre_in(pre+1+pos,p+1,n-1-pos);
	return h;
}
BTree* Creat_BTree_in_post(char *in,char *post,int n)
{
	BTree *h;
	char *p;
	if(n<=0) return NULL;
	h=new BTree();
	h->data=*(post+n-1);
	for(p=in;p<in+n;p++)
		if(*p==h->data) break;
	int pos=p-in;
	h->lc=Creat_BTree_in_post(in,post,pos);
	h->rc=Creat_BTree_in_post(p+1,post+pos,n-1-pos);
	return h;
}
void Display_BTree(BTree *h)
{
	if(h!=NULL)
	{
		cout<<h->data;
		if(h->lc!=NULL||h->rc!=NULL)
		{
			cout<<"(";
			Display_BTree(h->lc);
			if(h->rc!=NULL) cout<<",";
			Display_BTree(h->rc);
			cout<<")";
		}
	}
}
char pre[M],in[M],post[M]; //先序,中序,后序序列
int main()
{
	int n; //节点个数
	BTree *h;
	while(cin>>n)
	{
		cin>>pre>>in>>post;
		h=Creat_BTree_pre_in(pre,in,n);
		Display_BTree(h);
		cout<<endl;
		h=Creat_BTree_in_post(in,post,n);
		Display_BTree(h);
		cout<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值