二叉樹的創建

 前序、中序

#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct BTNode
{
	char data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;
BTNode *CreateBT(char pre[],char in[],int l1,int r1,int l2,int r2)
{
	BTNode *s;
	if(l1>r1)
	return NULL;
	s=(BTNode *)malloc(sizeof(BTNode));
	s->lchild=s->rchild=NULL;
	s->data=pre[l1];	
	int i;
	for(i=l2;i<=r2;++i)
		if(in[i]==pre[l1])
			break;
	s->lchild=CreateBT(pre,in,l1+1,l1+i-l2,l2,i-1);
	s->rchild=CreateBT(pre,in,l1+i-l2+1,r1,i+1,r2);
	return s;
}
void preorder(BTNode *T)
{
	if(T!=NULL)
	{
		cout<<T->data<<" ";
		preorder(T->lchild);
		preorder(T->rchild);	
	}
}
int main()
{
	BTNode *T;
	char pre[]="ABCDEFGH";
	char in[]="CBEDFAHG";
	T=CreateBT(pre,in,0,8,0,8);
	preorder(T);
}

 

  中序、後序

#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct BTNode
{
	char data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;
BTNode *CreateBT(char post[],char in[],int l1,int r1,int l2,int r2)
{

	BTNode *s;
	if(l1>r1)
	return NULL;
	s=(BTNode *)malloc(sizeof(BTNode));
	s->lchild=s->rchild=NULL;
	s->data=post[r1];
	int i;
	for(i=l2;i<r2;++i)
		if(in[i]==post[r1])
			break;
	s->lchild=CreateBT(post,in,l1,l1+i-l2-1,l2,i-1);
	s->rchild=CreateBT(post,in,l1+i-l2,r1-1,i+1,r2);
	return s;
} 
void preorder(BTNode *T)
{
	if(T!=NULL)
	{
		cout<<T->data<<" ";
		preorder(T->lchild);
		preorder(T->rchild);	
	}
}
int main()
{
	BTNode *T;
	char in[]="CBEDFAHG";
	char post[]="CEFDBHGA";
	T=CreateBT(post,in,0,8,0,8);
	preorder(T);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章