1.什么是线索二叉树
在二叉树的结点上加上线索的二叉树称为线索二叉树,对二叉树以某种遍历方式(如先序、中序、后序或层次等)进行遍历,使其变为线索二叉树的过程称为对二叉树进行线索化。 [1]
二叉树的遍历本质上是将一个复杂的非线性结构转换为线性结构,使每个结点都有了唯一前驱和后继(第一个结点无前驱,最后一个结点无后继)。对于二叉树的一个结点,查找其左右子女是方便的,其前驱后继只有在遍历中得到。为了容易找到前驱和后继,有两种方法。一是在结点结构中增加向前和向后的指针,这种方法增加了存储开销,不可取;二是利用二叉树的空链指针。
2.优点、缺点
优势
(1)利用线索二叉树进行中序遍历时,不必采用堆栈处理,速度较一般二叉树的遍历速度快,且节约存储空间。
(2)任意一个结点都能直接找到它的前驱和后继结点。 [2]
不足
(1)结点的插入和删除麻烦,且速度也较慢。
(2)线索子树不能共用。 [2]
3.代码实现(在vs2022环境下进行实现)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef char elemtype;
typedef enum
{
link,
thread
}pointerneg;
typedef struct bitnode
{
elemtype data;
struct bitnode* lchild, * rchild;
pointerneg lneg;
pointerneg rneg;
}bitnode,*bitree;
bitree pre;
//创建二叉树,用前序遍历
void creattree(bitree* t)
{
elemtype c;
scanf("%c", &c);
if (c == ' ')
{
(*t) = NULL;
}
else
{
(*t) = (bitnode*)malloc(sizeof(bitnode));
(*t)->data = c;
(*t)->lneg = link;
(*t)->rneg = link;
creattree(&(*t)->lchild);
creattree(&(*t)->rchild);
}
}
//寻找线索二叉树的规律,中序遍历
void ibthreading(bitree t)
{
if (t != NULL)
{
ibthreading(t->lchild);//遍历左
if (t->lchild == NULL)
{
t->lneg = thread;
t->lchild = pre;
}
if (pre->rchild == NULL)
{
pre->rneg = thread;
pre->rchild = t;
}
ibthreading(t->rchild);//遍历右
}
}
void inpandibthreading(bitree* t, bitree p)
{
(*t) = (bitnode*)malloc(sizeof(bitnode));
(*t)->lneg = link;
(*t)->rneg = thread;
(*t)->rchild = t;
if (p == NULL)
{
(*t)->lchild = t;
}
else
{
(*t)->lchild = p;
pre = *t;
ibthreading(p);
pre->rchild = (*t);
pre->rneg = thread;
(*t)->rchild = pre;
}
}
void visit(bitree t)
{
printf("%c", t->data);
}
void zhongpr(bitree t,int level)
{
if (t != NULL)
{
if (t->lneg == link)
{
zhongpr(t->lchild, level + 1);
}
visit(t);
if (t -> rneg == link)
{
zhongpr(t->rchild, level + 1);
}
}
}
int main()
{
bitree t = NULL;
bitree p = NULL;
int level = 1;
creattree(&t);
inpandibthreading(&p, t);
printf("中序排列结果为:");
zhongpr(t, level);
printf("\n");
return 0;
}