|
1鱼币
#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef enum{Link,Thread} PointerTag;
// 线索存储标志位
//Link(0):表示指向左右孩子的指针
//Thread(1):表示指向前去后继的线索
typedef struct BinThrNode
{
char data;
struct BinThrNode *lchild,*rchild;
PointerTag ltag;
PointerTag rtag;
}BinThrNode,*BinThrtree;
//全局变量,始终指向刚刚访问过的节点
BinThrTree pre;
void CreateBinThrtree(BinThrTree *T)
{
char c;
scanf("%c",&c);
if(' '== c )
{
*T = NULL;
}
else
{
*T =(BinThrNode *)malloc(sizeof(BinThrNode));
(*T)->data = c;
(*T)->ltag = Link;
(*T)->rtag = Link;
CreateBinTree(&(*T)->lchild);
CreateBinTree(&(*T)->rchild);
}
}
void InThreading(BinThrTree T)
{
if(T)
{
InThreading(T->lchild);//递归左孩子线索化
if(!T->lchild) //如果该节点没有左孩子,设置ltag为Thread,并把lchild指向上一个访问的节点
{
T->ltag = Thread;
T->lchild = pre;
}
if(!pre->rchild)
{
pre->rtag = Thread;
pre->rchild = T;
}
pre = T;
InThreading(T->rchild);
}
}
void InOrderThreading(BinThrTree *p,BinThrTree T)
{
*p = (BinThrtree)malloc(sizeof(BinThrNode));
(*p)->ltag = Link;
(*p)->rtag = Thread;
(*p)->rchild = *p;
if(!T)
{
(*p)->lchild = *p;
}
else
{
(*p)->lchild = T;
pre = *p;
InThreading(T);
pre->rchild = *p;
pre->rtag = Thread;
(*p)->rchild =pre;
}
}
//中序遍历二叉树,非递归
void visit(char c)
{
printf("%c",c);
}
void InOrderTraverse(BinThrTree T)
{
BinThrTree p;
p = T->lchild;
while(p != T)
{
while (p->ltag == Link)
{
p = p->lchild;
}
visit(p->data);
while(p->rtag == Thread && p->rchild!=T)
{
p = p->rchild;
visit(p->data);
}
p = p->rchild;
}
}
// P头指针 T头节点
int main()
{
BinThrTree P,T = NULL;
CreateBinThrTree(&T);
InOrderThreading(&P,T);
printf("中序遍历输出:\n");
InOrderTraverse( P );
printf("\n");
return 0;
}
我认为这段代码中中序遍历若不用递归的时候,那段非递归的代码有问题,
while(p->rtag == Thread && p->rchild!=T)
{
p = p->rchild;
visit(p->data);
}
初始化的时候,明明rtag都赋值为0了,什么时候变成的thread
还有就是中序遍历时,为什么处理节点在中间,不在开始啊
InThreading(T->lchild);//递归左孩子线索化
if(!T->lchild) //如果该节点没有左孩子,设置ltag为Thread,并把lchild指向上一个访问的节点
{
T->ltag = Thread;
T->lchild = pre;
}
if(!pre->rchild)
{
pre->rtag = Thread;
pre->rchild = T;
}
pre = T;
InThreading(T->rchild); |
|
|
|