先序序列:abc,,de,g,,f,,,
线索化输出:cbegdfa
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char ch;
struct node *lc;
struct node *rc;
int ltag;
int rtag;
}BiTree;
BiTree *pre;//设置前一结点指针
BiTree *creat(BiTree *root)
{
char c;
scanf("%c",&c);
if(c==',') root=NULL;
else
{
root=(BiTree *)malloc(sizeof(BiTree));
root->ch=c;
root->ltag=0;
root->rtag=0;//该结点既有左孩子,也有右孩子
root->lc=creat(root->lc);
root->rc=creat(root->rc);
}
return (root);
}
void InThreading(BiTree *root)
{
if(root!=NULL)//若二叉树不空
{
InThreading(root->lc);//线索化左子树
if(root->lc==NULL)
{
root->ltag=1;
root->lc=pre;
}//该结点左子树为空时,左标志置为1,指向其上一结点
if(pre->rc==NULL)
{
pre->rtag=1;
pre->rc=root;
}//若该结点右子树为空时,右标志置为1,上一结点的右孩子指向该结点
pre=root;//最后,上一结点指向该结点
InThreading(root->rc);//线索化右子树
}
}
void InOrderThreading(BiTree *p,BiTree *root)
{
p=(BiTree *)malloc(sizeof(BiTree));
p->ltag=0;
p->rtag=1;
p->rc=p;
if(root==NULL) p->lc=p;
else
{
p->lc=root;
pre=p;
InThreading(root);
pre->rc=p;
pre->rtag=1;
p->rc=pre;
}
}
void print(BiTree *root)
{
BiTree *p;
p=root->lc;
while(p!=root)
{
while(p->ltag!=1) p=p->lc;//一直找到最右边的结点
printf("%c",p->ch);
while(p->rtag==1&&p->rc!=root)
{
p=p->rc;
printf("%c",p->ch);
}//遍历左子树
p=p->rc;//遍历右子树
}
printf("%c",p->ch);
}
int main()
{
BiTree *root,p;
root=(BiTree *)malloc(sizeof(BiTree));
root=creat(root);
InOrderThreading(&p,root);
printf("中序遍历结果为:\n");
print(root);
printf("\n");
return 0;
}