定义
线索二叉树是一种物理结构,是表示前驱与后继位置关系的结构
示例
实现
先序线索化
过程
代码整合
//线索二叉树的类型定义
typedef struct node{
int data;//数据域
int ltag,rtag;//标志域:0-表示指向孩子,1-表示指向前驱或后继
struct node *lchild,*rchild;//指针域
}bithrnode,*bithrtree;
//bithrtree bt;
//中序线索化:左根右
1.判断树非空
2.不断递归中序遍历左子树,指针域为空线索化结点(改指前驱,标志置1)
3.前驱非空且指针域为空线索化前驱(改指后继,标志置1)
4.记录前驱,不断线索化右子树
void inthread(bithrtree b){
bithrnode *p=b,*pre;
if(p!=NULL){
inthread(p->lchild);
if(p->lchild==NULL){
p->lchild=pre;
p->ltag=1;
}
if(pre!=NULL&&pre->rchild==NULL){
pre->rchild=p;
pre->rtag=1;
}
pre=p;//记录
inthread(p->rchild);
}
}
//找中序线索二叉树的首结点:即找树中最左边的孩子
1.空树,返回0
2.当标志为左孩子时,不断遍历左孩子
3.返回结点
bithrnode * first(bithrtree b){
bithrnode *p=b;
if(p==NULL) return 0;
while(p->ltag==0) p=p->lchild;
return p;
}
//找中序线索二叉树的直接后继:右标志位为1的右指针,或右子树中的最左边结点(左根右(左根右))
1.右标志位为1时,记录右指针
2.右标志位为0时,找最左边结点
3.返回结点
bithrnode * next(bithrtree b){
bithrnode *p=b,*q;
if(p->rchild==1) q=p->rchild;
else{
for(p=p->rchild;p->ltag==0;p=p->lchild)
q=p;
return q;
}
}
//遍历中序线索二叉树
1.树非空:访问第一个结点
2.访问下一个结点
void threadin(bithrtree b){
bithrnode *p;
p=first(b);
while(p!=NULL){
cout<<p->data<<endl;
p=next(p);
}
}