# 数据结构（十四） 线索二叉树讲解(不带头节点中序加线索) 以及实现的完整代码

//为二叉链表加中序线索化 (不带头节点)
#include <iostream>

using namespace std;
//线索化的结构体
typedef struct Node
{
char data;
int ltag;
int rtag;
struct Node *lchild;
struct Node *rchild;
}*BiTree;
//pre为前驱节点。为全局变量 ,初始化时右子树为空
BiTree pre;
//中序实现创建二叉树
void createBiTree(BiTree &Tree)
{
char data;
cin>>data;
if(data=='#')
{
Tree = NULL;
}
else
{

Tree = new Node();
Tree->data = data;
Tree->ltag = 0;
Tree->rtag=0;
createBiTree(Tree->lchild);
createBiTree(Tree->rchild);
}
}
//中序线索化的实现
void function(BiTree &Tree)
{
if(Tree)
{
function(Tree->lchild);

if(Tree->lchild==NULL)
{
Tree->ltag=1;
Tree->lchild=pre;
}
if(pre->rchild==NULL)
{
pre->rtag=1;
pre->rchild=Tree;
}
pre = Tree;

function(Tree->rchild);

}
}
//中序遍历  左根右
void preBiTree(BiTree Tree)
{
if(Tree==NULL)
{
cout<<"是空数\n";
exit(1);
}
while(Tree!=NULL)
{
while(Tree!=NULL&&Tree->ltag==0)
{
Tree = Tree->lchild;
}
cout<<Tree->data<<" ";
while(Tree!=NULL&&Tree->rtag==1)
{
Tree = Tree->rchild;
cout<<Tree->data<<" ";

}
Tree=Tree->rchild;
}
}
int main()
{
BiTree Tree;
cout<<"请输入你要创建的二叉树的数据(按先序遍历创建的二叉树#为空节点的表示)\n";
createBiTree(Tree);
pre = new Node();
pre->lchild=NULL;
function(Tree);
preBiTree(Tree);
return 0;
}

01-19 1058

10-30 1189

03-20 6595

05-11 1775

03-01 4762

10-09 6841

11-02 2005

03-26 1867

05-03 2612

08-01 2.5万