二叉树中的线索化问题,数据结构最核心、密集的考点之一:树,以中序二叉树的线索化
代码参考王道数据结构课程!
#include<stdio.h>
#include<stdlib.h>
//创建链二叉数结构,并设置两个标志位tag用来表示
//左孩子和有孩子是否线索化
typedef struct BiNode {
char data;
struct BiNode* lchild, * rchild;
int ltag, rtag;
}*Bitree;
BiNode* pre = NULL;
void Initialtree(Bitree* t)
{//初始化
*t = NULL;
}
void Creattree(Bitree *t)
{
//传统的递归建立链树的过程
char c;
scanf_s("%c", &c);
if (c=='#')
{
*t = NULL;
}
else {
*t = (Bitree)malloc(sizeof(BiNode));
(*t)->data = c;
Creattree(&(*t));
Creattree(&(*t));
}
}
void visit(Bitree t)
{
//访问B树,当该节点的左孩子为空时,
//代表有空的链域出现,此时将这个空链域线索化
if (t->lchild == NULL)
{
t->lchild = pre;
t->ltag = 1;
}
//当pre指针指向的不是最后一个节点并且没有右孩子时
//让右空链域线索化
if (pre != NULL && pre->rchild==NULL)
{
pre->rchild = t;
pre->rtag = 1;
}
//让pre指向下一个遍历的节点
pre = t;
}
void thread(Bitree t)
{
//中序遍历,左中右的顺序
if (t != NULL)
{
thread(t->lchild);
visit(t);
thread(t->rchild);
}
}
void Creathread(Bitree t)
{
//线索化主函数,让指针pre按照中序遍历进行扫描顺便线索化
pre = NULL;
if (t != NULL)
{
thread(t);
if (pre->rchild == NULL)
pre->rtag = 1;
}
}
int main()
{
//主函数,很简单,不解释了
printf("请输入需要存放进二叉树的数据,以#结尾!\n");
Bitree t;
Initialtree(&t);
Creattree(&t);
Creathread(t);
getchar();
//
return 0;
}