//链式存储结构
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
//声明结构体
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}BTNode;
char apre[]="ABDGCEF",ai[]="DGBAECF",apost[]="GDBEFCA";
int len;
//用先序序列和中序序列创建二叉树
BTNode* CreatBT1(char *pre,char *in,int n)
{
BTNode *b;
char *p;
int k;
if(n<=0) return NULL;
b=(BTNode*)malloc(sizeof(BTNode));
b->data=*pre;
for(p=in;p<in+n;p++)
if(*p==*pre) break;
k=p-in; //k是记录的当前根节点的左右结点的个数
b->lchild=CreatBT1(pre+1,in,k);
b->rchild=CreatBT1(pre+k+1,p+1,n-k-1);
return b;
}
//用中序序列和后续序列创建二叉树
//BTNode* CreatBT2(char *post,char *in,int n)
//{
// BTNode *b;
// char *p;
// int k;
// if(n<=0) return NULL;
//
//}
//先序遍历
void PreOrder(BTNode* bt)
{
if(bt!=NULL)
{
cout<<bt->data<<"*";
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
//中序遍历
void InOrder(BTNode *bt)
{
if(bt!=NULL)
{
InOrder(bt->lchild);
cout<<bt->data<<"*";
InOrder(bt->rchild);
}
}
//后序遍历
void PostOrder(BTNode *bt)
{
if(bt!=NULL)
{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout<<bt->data<<"*";
}
}
int main()
{
len=strlen(apre);
//用先序序列和中序序列创建二叉树
BTNode*bt = CreatBT1(apre,ai,len);
//先序遍历
PreOrder(bt); cout<<endl;
//用中序序列和后续序列创建二叉树
return 0;
}
用二叉链创建二叉树(顺序表等更?)
猜你喜欢
转载自blog.csdn.net/qq_43346054/article/details/102966976
今日推荐
周排行