数据结构–二叉树的线索化
用土办法找到中序前驱
typedef struct BiTNode
{
ElemType data; //数据域
struct BiTNode *lchild, *rchild; //左、右孩子指针
struct BiTnode *parent; //父节点指针
}BiTNode, *BiTree;
BiTNode *p; // p指向目标结点
BiTNode *pre = NULL; //指向当前访问结点的前驱
BiTNode *final = NULL; //用于记录最终结果
void visit(BiTNode* q)
{
if (p == q)
final = pre;
else
pre = q;
}
void InOrder(BiTree T)
{
if (T != NULL)
{
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
中序遍历序列:D G B E A F C
中序线索化
typedef struct ThreadNode
{
ElemType data;
struct ThreadNode *lchild, *rchild;
int ltag, rtag; //左、右线索标志
}ThreadNode, *ThreadTree;
ThreadNode *pre = NULL; //指向当前访问结点的前驱
void visit(ThreadNode* q)
{
if (q->lchild != NULL) //左子树为空,建立前驱线索
q->lchild = pre, q->ltag = 1;
if (pre != NULL && pre->rchild == NULL) //建立前驱结点的后继线索
pre->rchild = q, pre->rtag = 1;
pre = q;
}
void InThread(ThreadTree T)
{
if (T != NULL)
{
InThread(T->lchild);
visit(T);
InThread(T->rchild);
}
}
void CreateInThread(ThreadTree T)
{
pre = NULL;
if (T != NULL)
{
InThread(T);
if (pre->rchild == NULL) //处理遍历的最后一个结点
pre->rtag = 1;
}
}
先序线索化
typedef struct ThreadNode
{
ElemType data;
struct ThreadNode *lchild, *rchild;
int ltag, rtag; //左、右线索标志
}ThreadNode, *ThreadTree;
ThreadNode *pre = NULL; //指向当前访问结点的前驱
void visit(ThreadNode* q)
{
if (q->lchild != NULL) //左子树为空,建立前驱线索
q->lchild = pre, q->ltag = 1;
if (pre != NULL && pre->rchild == NULL) //建立前驱结点的后继线索
pre->rchild = q, pre->rtag = 1;
pre = q;
}
void PreThread(ThreadTree T)
{
if (T != NULL)
{
visit(T);
if (T->ltag == 0)
PreThread(T->lchild);
PreThread(T->rchild);
}
}
void CreatePreThread(ThreadTree T)
{
pre = NULL;
if (T != NULL)
{
PreThread(T);
if (pre->rchild == NULL) //处理遍历的最后一个结点
pre->rtag = 1;
}
}
后序线索化
typedef struct ThreadNode
{
ElemType data;
struct ThreadNode *lchild, *rchild;
int ltag, rtag; //左、右线索标志
}ThreadNode, *ThreadTree;
ThreadNode *pre = NULL; //指向当前访问结点的前驱
void visit(ThreadNode* q)
{
if (q->lchild != NULL) //左子树为空,建立前驱线索
q->lchild = pre, q->ltag = 1;
if (pre != NULL && pre->rchild == NULL) //建立前驱结点的后继线索
pre->rchild = q, pre->rtag = 1;
pre = q;
}
void PostThread(ThreadTree T)
{
if (T != NULL)
{
PostThread(T->lchild);
PostThread(T->rchild);
visit(T);
}
}
void CreatePostThread(ThreadTree T)
{
pre = NULL;
if (T != NULL)
{
PostThread(T);
if (pre->rchild == NULL) //处理遍历的最后一个结点
pre->rtag = 1;
}
}