#include<iostream>
using namespace std;
typedef char Elemtype;
typedef enum{LINK=0,THREAD=1}linktype;
typedef struct BiThNode
{
Elemtype data;
BiThNode *leftchild;
BiThNode *rightchild;
linktype ltag;
linktype rtag;
}BiThNode;
BiThNode *BuyNode()
{
BiThNode *ptr = new BiThNode;
if(ptr == NULL) return NULL;
memset(ptr,0,sizeof(BiThNode));
return ptr;
}
void freeNode(BiThNode *p)
{
delete p;
}
//建树
BiThNode *builttree(Elemtype *&ptr)
{
BiThNode *s = NULL;
while(ptr != NULL && *ptr != '#')
{
s = BuyNode();
s->data = *ptr;
s->leftchild = builttree(++ptr);
s->rightchild = builttree(++ptr);
}
return s;
}
//中序遍历
void Miinoder(BiThNode *p)
{
if(p != NULL)
{
Miinoder(p->leftchild);
cout<<p->data<<" ";
Miinoder(p->rightchild);
}
}
//用递归线索话一颗二叉树
//1.传参的
void Thread(BiThNode *p, BiThNode *&ptr)
{
if(p != NULL)
{
Thread(p->leftchild,ptr);
if(p->leftchild == NULL)
{
p->ltag = THREAD;
p->leftchild = ptr;
}
if(ptr != NULL && ptr->rightchild == NULL)
{
ptr->rightchild = p;
ptr->rtag = THREAD;
}
ptr = p;
Thread(p->rightchild,ptr);
}
}
void MakeThread(BiThNode *p)
{
if(p == NULL) return ;
BiThNode *ptr = NULL;
Thread(p,ptr);
ptr->rtag = THREAD;
ptr->rightchild = NULL;
}
//2.有个全局变量
BiThNode *ptr = NULL;
void MakeThread1(BiThNode *p)
{
if(p != NULL)
{
MakeThread1(p->leftchild);
if(p->leftchild == NULL)
{
p->ltag = THREAD;
p->leftchild = ptr;
}
if(ptr != NULL && ptr->rightchild == NULL)
{
ptr->rightchild = p;
ptr->rtag = THREAD;
}
ptr = p;
MakeThread1(p->rightchild);
}
}
/*
main()中是这样是{ ptr->rtag = THREAD;
ptr->rightchild = NULL;}
*/
//中序遍历一颗线索二叉树
BiThNode *First(BiThNode *p)
{
while(p != NULL && p->ltag != THREAD)
{
p = p->leftchild;
}
return p;
}
BiThNode *Next(BiThNode *p)
{
if(p == NULL) return NULL;
if(p->rtag == LINK)
{
BiThNode *ptr = First(p->rightchild);
return ptr;
}
else
{
return p->rightchild;
}
}
void ThreadMiinder(BiThNode *p)
{
for(BiThNode *s = First(p);s != NULL;s = Next(s))
{
cout<<s->data<<" ";
}
cout<<endl;
}
int main()
{
char *str = "ABC##DE##F##G#H##";
BiThNode *root = NULL;
BiThNode *ptr = NULL;
root = builttree(str);
MakeThread(root);
ThreadMiinder(root);
/*Miinoder(root);
cout<<endl;*/
return 0;
}
线索二叉树的建立和中序遍历
最新推荐文章于 2022-07-24 09:29:31 发布