#include<bits/stdc++.h>
using namespace std;
//定义
typedef struct ThreadNode
{
char data;
ThreadNode *lchild,*rchild;
int ltag,rtag;//0代表孩子,1代表后继
}ThreadNode,*ThreadTree;
//建一棵二叉树
ThreadTree Create()
{
ThreadTree tt;
char ch;
cin>>ch;
if(ch=='#')
{
tt=NULL;
}
else
{
tt=(ThreadNode*)malloc(sizeof(ThreadNode));
tt->data=ch;
tt->lchild=Create();
tt->rchild=Create();
tt->ltag=0;
tt->rtag=0;
}
}
//二叉树线索化
void InThread(ThreadTree &p,ThreadTree &pre)//pre是刚刚访问过的节点
{
if(p!=NULL)
{
InThread(p->lchild,pre);
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,pre);
}
}
void CreateInThread(ThreadTree tt)
{
ThreadTree pre=NULL;
if(tt!=NULL)
{
InThread(tt,pre);
pre->rchild=NULL;
pre->rtag=1;
}
}
//中序线索二叉树的遍历
ThreadNode *FirstNode(ThreadNode *p)
{
while(p->ltag==0)
{
p=p->lchild;
}
return p;
}
ThreadNode *NextNode(ThreadNode *p)
{
if(p->rtag==0)
return FirstNode(p->rchild);
else
return p->rchild;
}
void InOrder(ThreadNode *tt)
{
for(ThreadNode *p=FirstNode(tt);p!=NULL;p=NextNode(p))
{
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
ThreadTree tt=Create();
CreateInThread(tt);
InOrder(tt);
}
线索二叉树基础
最新推荐文章于 2024-08-24 23:00:16 发布