中序线索化及遍历
终于把二叉树搞完了
跟着王道的课走了几遍,终于把中序线索树的生成和遍历搞定了,这玩意做题思路还挺清晰,写代码真是折磨人啊
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node* pleft;
struct Node* pright;
int tagleft;
int tagright;
}node, * pnode;
node *pre = NULL;
void inthread(pnode T)
{
if (T != NULL)
{
inthread(T->pleft);
visit(T);
inthread(T->pright);
}
}
void visit(pnode p)//中序线索化
{
if (p->pleft==NULL)
{
p->pleft = pre;
p->tagleft = 1;
}
if (pre != NULL && pre->tagright==NULL)
{
pre->pright = p;
pre->tagright = 1;
}
pre = p;
//此时pre指向最后一个节点
//在调用时,最后需要将pre的右指针置为null
}
pnode findnext(pnode p)
{
if (p->tagright == 1)//p没有右节点,右节点存放的就是下个节点
{
return p->pright;
}
else
{
while (p->tagleft == 0)p = p->pleft;//找到最左的节点
}
return p;
}