c/c++实现线索二叉树及其中序遍历和查找
#include<stdio.h>
#include<stdlib.h>
typedef char DataType;
typedef struct {
int ltag,rtag;
DataType data;
struct node *lchild,*rchild;
}ThreadNode,*ThreadTree;
//inorder thread tree
void inThread(ThreadTree t,ThreadTree pre)//before being called pre is null
{
if(t)
{
inThread(t->lchild,pre);
if(!t->lchild)
{
t->ltag=1;
t->lchild=pre;
}
if(!t->rchild)
t->rtag=1;
if(pre && pre->rtag==1)
pre->rchild=t;
pre=t;
inTread(t->rchild,pre);
}
}
ThreadTree inPreNode(ThreadTree p)//get the prenode of p
{
ThreadTree pre;
pre=p->lchild;
if(p.ltag==0)
while(pre->rtag==0) pre=pre->rchild;
return pre;
}
ThreadTree inPostNode(ThreadTree p)//get the postnode of p
{
ThreadTree post;
post=p->rchild;
if(p.rtag==0)
while(post->ltag==0) post=post->lchild;
return post;
}
//traverse the thread tree
void inOrder(ThreadTree t)
{
ThreadTree p;
if(t)
{
p=t;
while(p->ltag==1) p=p->lchild;
while(p)
{
visit(p->data);
p=inPostNode(p);//get the postnode of p
}
}
}
//search for node of x
ThreadTree inOrder(ThreadTree t,DataType x)
{
ThreadTree p;
if(t)
{
p=t;
while(p->ltag==1) p=p->lchild;
while(p)
{
if(p->data==x)
break;
p=inPostNode(p);//get the postnode of p
}
}
return p;
}