一、线索二叉树的概念
- 线索:指向前驱和后继的指针
- 线索链表:加上线索的二叉链表
- 线索二叉树:加上线索的二叉树(相当于一个双向链表)
- 线索化:对二叉树以某种次序遍历使其变为线索二叉树的过程
我们在每个结点新增设两个标志域:Ltag和rtag分别用来指向前驱和后继
- Ltag和rtag只是存放0或1数字的布尔型变量
- Ltag为0时指向该节点的左孩子,为1时指向该结点的前驱
- Ltag为0时指向该节点的右孩子,为1时指向该结点的后继
二、线索二叉树结构的实现:
typedef enum {
Link, Thread } Pointertag;
typedef struct BiThrTree
{
char data;
struct BiThrTree* lchild, * rchild;
Pointertag ltag;
Pointertag rtag;
}BiThrNode,*BiThrTree;
中序遍历进行中序线索化
BiThrTree pre;
void InThreading(BiThrTree p)
{
if(p)
{
InThreading(p->lchild);
if(!p->lchild)
{
p->ltag=Thread;
p->lchild=pre;
}
if(!pre->rchild)
{
pre->rtag=Thread;
pre->rchild=p;
}
pre=p;
InThreading(p->rchild);
}
}
和双向链表结构一样,在二叉树线索链表上添加一个头结点
void Inorder(BiThrTree T)
{
BiThrTree p ;
p=T->lchild;
while (p!=T)
{
while (p->ltag == Link)
{
p = p->lchild;
}
printf("%c", p->data);
while (p->rtag == Thread && p->rchild!=T)
{
p = p->rchild;
printf("%c", p->data);
}
p = p->rchild;
}
}
如果所用的二叉树需经常遍历或查找结点时需要某种遍历序列中的前驱和后继,那么采用线索二叉链表!
三、代码实现
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int Max ( int a, int b )
{
return a > b ? a : b;
}
AVLTree SingleLeftRotation ( AVLTree A )
{
AVLTree B = A->Left;
A->Left = B->Right;
B->Right = A;
A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;
B->Height = Max( GetHeight(B->Left), A->Height ) + 1;
return B;
}
AVLTree DoubleLeftRightRotation ( AVLTree A )
{
A->Left = SingleRightRotation(A->Left);
return SingleLeftRotation(A);
}
AVLTree Insert( AVLTree T, ElementType X )
{
if ( !T ) {
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = X;
T->Height = 0;
T->Left = T->Right = NULL;
}
else if ( X < T->Data ) {
T->Left = Insert( T->Left, X);
if ( GetHeight(T->Left)-GetHeight(T->Right) == 2 )
if ( X < T->Left->Data )
T = SingleLeftRotation(T);
else
T = DoubleLeftRightRotation(T);
}
else if ( X > T->Data ) {
T->Right = Insert( T->Right, X );
if ( GetHeight(T->Left)-GetHeight(T->Right) == -2 )
if ( X > T->Right->Data )
T = SingleRightRotation(T);
else
T = DoubleRightLeftRotation(T);
}
T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1;
return T;
}