typedef struct BiTNode{
char data;
BiTNode* lchild, *rchild;
int lflag, rflag;
}BiTree;
//中序线索化
void InThreading(BiTree* t){
if (t != NULL)
{
InThreading(t->lchild);//找到属于叶节点的左孩子
if (t->lchild == NULL)
t->lflag = 1;
if (t->rchild == NULL)
t->rflag = 1;
if (current != NULL){
if (t->lflag == 1)
t->lchild = current;
if (current->rflag == 1)
current->rchild = t;
}
current = t;
InThreading(t->rchild);
}
}
//前序线索化
void FiThreading(BiTree* t){
if (t != NULL){
if (t->lchild == NULL)
{
t->lflag = 1;
if (current != NULL)
t->lchild = current;
}
if (t->rchild == NULL)
{
t->rflag = 1;
if (current ->rflag==1)
current->rchild = t;
}
current = t;
//cout << "currrent=" << current->data << endl;
if (t->lflag==0)//一定要加上标志位判断,否则会陷入死循环
FiThreading(t->lchild);
if (t->rflag==0)//一定要加上标志位判断,否则会陷入死循环
FiThreading(t->rchild);
}
}
//中序线索二叉树遍历
/*
思路:先查找中序遍历序列的开始节点,沿左指针往下查找,
直到找到无左孩子的节点即二叉树中最左下的节点,将其
输出。继续查找节点的中序后继节点,直到终端节点。
节点的中序后继节点分两种情况:若节点t的右子树为空,
则t->rchild直接指向t的中序后继节点;若节点t的右子树
不为空,则从其右子树开始,沿左指针往下查找,直到找到
节点t的右子树最左下的节点,就是它的中序后继节点
*/
void VisitByIn(BiTree* t){
while (t != NULL){
while (t->lflag == 0)
t = t->lchild;
if (t == NULL)
return;
cout << t->data << endl;
while (t->rflag == 1 && t->rchild != NULL){
t = t->rchild;
cout << t->data << endl;
}
t = t->lchild;
}
}
//前序线索二叉树遍历
/*
思路:
先依次沿左指针输出节点信息,直到找到无左孩子的节点,
将其输出。继续查找节点的前序后继节点,将其输出。
此前序后继节点t的情况分两种,若t的左子树不为空,
则从其左子树开始,沿左指针向下查找并输出,直到最下。
若t的左子树为空,则t->rchild指向t的前序后继节点,
输出
*/
void VisitByFi(BiTree* t){
while (t != NULL){
while (t->lflag==0){
cout << t->data << endl;
t = t->lchild;
}
if (t == NULL)
return;
cout << t->data << endl;
t = t->rchild;
if (t == NULL)
return;
cout << t->data << endl;
while (t->lflag == 1 && t->rchild != NULL)//注意这儿是要判断左标置位
{
t = t->rchild;
cout << t->data << endl;
}
t = t->lchild;
}
}