数据结构》树(2)中序二叉树 完整源码

#include <iostream>
#include <windows.h>
using namespace std;
typedef char ElemType;
typedef enum{
link,
thread
}pointertag;
typedef struct mtnode{
ElemType data;
struct mtnode *lchild;
struct mtnode *rchild;
pointertag ltag,rtag;
}MTNode,*MTree;
bool create_mtree(MTree &t);
void add_link(MTree t);
void in_threading(MTree t);
bool inorder_threading(MTree &thrt,MTree T);
void inorder_traver(MTree t);
MTree pre;
int main()
{
MTree t;
MTree thrt;
cout<<"中序线索二叉树\n";
create_mtree(t);
add_link(t);
inorder_threading(thrt,t);
inorder_traver(thrt);
cout<<endl;
return 0;
}
bool create_mtree(MTree &t)
{
ElemType data;
cin>>data;
if(data == '#')
t = NULL;
else
{
t = new MTNode;
if(!t)
return false;
t->data = data;
create_mtree(t->lchild);
create_mtree(t->rchild);
}
return true;
}
void add_link(MTree t)
{
if(t)
{
if(t->lchild)
t->ltag = link;
if(t->rchild)
t->rtag = link;
add_link(t->lchild);
add_link(t->rchild);
}
}
void in_threading(MTree t)
{
if(t)
{
in_threading(t->lchild);
if(!t->lchild)
{
t->ltag = thread;
t->lchild = pre;
}
if(!pre->rchild)
{
pre->rtag = thread;
pre->rchild = t;
}
pre = t;
in_threading(t->rchild);
}
}
bool inorder_threading(MTree &thrt,MTree t)
{
thrt = new MTNode;
if(!thrt)
return false;
thrt->ltag = link;
thrt->rtag = thread;
thrt->rchild = thrt;
if(!t)
thrt->lchild = thrt;
else
{
thrt->lchild = t;
pre = thrt;
in_threading(t);
pre->rchild = thrt;
pre->rtag = thread;
thrt->rchild = pre;
}
return true;
}
void inorder_traver(MTree t)
{
MTree p = t->lchild;
while(p != t)
{
while(p->ltag == link)
p = p->lchild;
cout<<p->data<<" ";
while(p->rtag == thread && p->rchild != t)
{
p = p->rchild;
cout<<p->data<<" ";
}
p = p->rchild;
}
}