n个结点的二叉链表中含有n+1(2n-(n-1)=n+1)个空指针域。利用二叉链表中的空指针域,存放指向结点在某种遍历次序下的前趋和后继结点的指针(这种附加的指针称为"线索")。
//线索二叉树及函数
#include
using namespace std;
struct node{
int data;
node* lchild,*rchild;
bool is_thread_l,is_thread_r;
};//线索二叉树
void f_thread(node*t,node*&pre); //辅助,中序线索化二叉树
void f_thread_tree(node* t);//中序线索化二叉树
node* f_seek_first(node*t);//找树的第一个结点
node* f_seek_first(node*t);//找该结点的下一个结点
void f_travel_thread(node*t);//利用线索进行中序遍历
void f_thread_tree(node* t){
node*pre=NULL;
f_thread(t,pre);
pre->is_thread_r=1;
//对最后一个叶结点做处理,原指针域为空的都有相应的is_thread_r/l 标记
}
node* f_seek_first(node*t){
if(!t) return NULL;
while(t->is_thread_l==false) t=t->lchild;
return t;
}
node* f_seek_next(node*t){
if(!t) return NULL;
if(t->is_thread_r) return t->rchild;
return f_seek_first(t->rchild);
}
void f_travel_thread(node*t){
node*p=f_seek_first(t);
for(;p;f_seek_next(p))
cout<data;
}
void f_thread(node*t,node*&pre){
if(t){
f_thread(t->lchild,pre);
if(pre&&pre->rchild ==NULL){
pre->is_thread_r=1;
pre->rchild=t;
}
if(t->lchild==NULL){
t->lchild=pre;
t->is_thread_l=1;
}
pre=t;
f_thread(t->rchild,pre);
}
}