您的位置:首页 > 其它

二叉树的链式存储和基本操作

2017-11-07 11:33 411 查看
上一篇介绍了二叉树的顺序存储结构,这一篇介绍链式存储结构,定义结点由三部分组成:数据域、左孩子结点指针、右孩子结点指针;下边是实现代码:

typedef struct Btree
{
ElemType data;
struct Btree *Lchild;
struct Btree *Rchild;
}BTree;
//init
BTree* BTree_Init(ElemType e)
{
BTree *head;
head=(BTree *)malloc(sizeof(BTree));
head->data=e;
head->Lchild=NULL;
head->Rchild=NULL;
return head;
}
//insert left
int BTree_insertLeft(BTree *T,ElemType e)
{
BTree *p;
p=(BTree *)malloc(sizeof(BTree));
p->data=e;
if(T->Lchild!=NULL)
{
p->Lchild=T->Lchild;
p->Rchild=NULL;
T->Lchild=p;
}
else
{
p->Lchild=p->Rchild=NULL;
T->Lchild=p;
}
return 1;
}
int BTree_insertRight(BTree *T,ElemType e)
{
BTree *p;
p=(BTree *)malloc(sizeof(BTree));
p->data=e;
if(T->Rchild!=NULL)
{
p->Rchild=T->Rchild;
p->Lchild=NULL;
T->Rchild=p;
}
else
{
p->Lchild=p->Rchild=NULL;
T->Rchild=p;
}
return 1;
}
//
bool isEmpty(BTree *T)
{
return T->data!='A';
}
//
void destroy_1(BTree *T)
{
if(T->Lchild!=NULL)
destroy_1(T->Lchild);
if(T->Rchild!=NULL)
destroy_1(T->Rchild);
cout<<"destroy : "<<T->data<<endl;
free(T);
}
//Traver
//前序
void traver_1(BTree *T)
{
cout<<T->data<<" ";
if(T->Lchild!=NULL)
traver_1(T->Lchild);
if(T->Rchild!=NULL)
traver_1(T->Rchild);
}
//中序
void traver_2(BTree *T)
{
if(T->Lchild!=NULL)
traver_1(T->Lchild);
cout<<T->data<<" ";
if(T->Rchild!=NULL)
traver_1(T->Rchild);
}
//后序
void traver_3(BTree *T)
{/*
if(T->Lchild!=NULL)
traver_1(T->Lchild);
if(T->Rchild!=NULL)
traver_1(T->Rchild);
cout<<T->data<<" ";
*/
if(T!=NULL)
{
traver_3(T->Lchild);
traver_3(T->Rchild);
cout<<T->data<<" ";
}
}

上一篇给出了遍历操作的递归和非递归实现,这一篇链式存储结构遍历的非递归算法,读者可以根据上一篇的代码自行实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: