主题:[原创]贴下自己写的二叉树中序线索化算法的实现 (ANSI C)
最近开始猛攻树这块了。看了老严书上P134的算法6.6和6.7,然后我自己写了一个。没有采用书上的方法使用全局变量pre,而是把递归函数的参数增加到二个,同时返回线索化后序列中最后的节点,依此来实现递归。
实现与老严的略有不同。希望大家多指点。
//BinThreadTree InOrderThreading(BinThreadTree T)
//线索化T并返回头节点,要求线索二叉树T未必线索化
typedef enum _PointerTag{LINK, THREAD} PointerTag;
typedef struct _BinThreadTreeNode
{
struct _BinThreadTreeNode *left;
struct _BinThreadTreeNode *right;
PointerTag left_tag:4;
PointerTag right_tag:4;
TElemType data;
} *BinThreadTree;
BinThreadTree InOrderThreading_pre(BinThreadTree T, BinThreadTree pre);
BinThreadTree InOrderThreading(BinThreadTree T)
{
BinThreadTree Thrt;
Thrt = (BinThreadTree)malloc(sizeof(struct _BinThreadTreeNode));
/*if (NULL = Thrt)
{
FatalError(none_mem);
}*/
if (NULL == T)
{
Thrt->left_tag = Thrt->right_tag = THREAD;
Thrt->left = Thrt->right = Thrt;
}
else
{
Thrt->left_tag = LINK;
Thrt->left = T;
Thrt->right_tag = THREAD;
(Thrt->right = InOrderThreading_pre(T, Thrt))->right = Thrt;
}
return Thrt;
}
BinThreadTree InOrderThreading_pre(BinThreadTree T, BinThreadTree pre)
{
if (NULL == T->left)
{
T->left_tag = THREAD;
T->left = pre;
}
else
{
T->left_tag = LINK;
InOrderThreading_pre(T->left, pre)->right = T;
}
if (NULL == T->right)
{
T->right_tag = THREAD;
return T;
}
else
{
T->right_tag = LINK;
return InOrderThreading_pre(T->right, T);
}
}
实现与老严的略有不同。希望大家多指点。
//BinThreadTree InOrderThreading(BinThreadTree T)
//线索化T并返回头节点,要求线索二叉树T未必线索化
typedef enum _PointerTag{LINK, THREAD} PointerTag;
typedef struct _BinThreadTreeNode
{
struct _BinThreadTreeNode *left;
struct _BinThreadTreeNode *right;
PointerTag left_tag:4;
PointerTag right_tag:4;
TElemType data;
} *BinThreadTree;
BinThreadTree InOrderThreading_pre(BinThreadTree T, BinThreadTree pre);
BinThreadTree InOrderThreading(BinThreadTree T)
{
BinThreadTree Thrt;
Thrt = (BinThreadTree)malloc(sizeof(struct _BinThreadTreeNode));
/*if (NULL = Thrt)
{
FatalError(none_mem);
}*/
if (NULL == T)
{
Thrt->left_tag = Thrt->right_tag = THREAD;
Thrt->left = Thrt->right = Thrt;
}
else
{
Thrt->left_tag = LINK;
Thrt->left = T;
Thrt->right_tag = THREAD;
(Thrt->right = InOrderThreading_pre(T, Thrt))->right = Thrt;
}
return Thrt;
}
BinThreadTree InOrderThreading_pre(BinThreadTree T, BinThreadTree pre)
{
if (NULL == T->left)
{
T->left_tag = THREAD;
T->left = pre;
}
else
{
T->left_tag = LINK;
InOrderThreading_pre(T->left, pre)->right = T;
}
if (NULL == T->right)
{
T->right_tag = THREAD;
return T;
}
else
{
T->right_tag = LINK;
return InOrderThreading_pre(T->right, T);
}
}