线索二叉树,是将一个二叉树叶子节点未使用到的指针,指向中序遍历结果当中的前一个节点或后一个节点。
这样在进行中序遍历的时候,就无需用递归的方法,只需线性即可中序遍历。
下面先建立一个基本的二叉树
下面开始中序遍历线索化
下面开始线性中序遍历
完整代码
#include <iostream>
#include <string>
using namespace std;
struct DataNode {char s;};
enum PointerTag {Link,Thread};
typedef struct BiThrNode {
DataNode data;
struct BiThrNode *lchild, *rchild;
PointerTag ltag, rtag;
}BiThrNode, *BiThrTree;
BiThrTree pre;
void CreatBiTree(BiThrTree &tree, string str, int length, int index) {
if (index <= length) {
tree = (BiThrTree)malloc(sizeof(BiThrNode));
DataNode Data;
Data.s = str.at(index-1);
tree->data = Data;
tree->lchild = NULL;
tree->rchild = NULL;
tree->ltag = Link;
tree->rtag = Link;
CreatBiTree(tree->lchild, str, length, 2 * index);
CreatBiTree(tree->rchild, str, length, 2 * index + 1);
}
}
void InThreading(BiThrTree tree) {
if (tree) {
if (tree->lchild)InThreading(tree->lchild);
if (!tree->lchild) { //叶子节点的左边是pre节点,将它指向中序遍历的前一个节点(1)
tree->ltag = Thread;
tree->lchild = pre;
}
if (pre != NULL && !pre->rchild) { //执行与(1)相反的操作
pre->rtag = Thread;
pre->rchild = tree;
}
pre = tree; //保存当前节点为pre,以便中序遍历下一节点使用
if (tree->rchild)InThreading(tree->rchild);
}
}
void InOrderThreading(BiThrTree tree) {
BiThrTree p = tree;
while (p) {
while (p->ltag == Link) {
p = p->lchild;
}
cout << p->data.s << " ";
while (p->rtag == Thread && p->rchild != NULL) {
p = p->rchild;
cout << p->data.s << " ";
}
p = p->rchild;
}
}
int main()
{
BiThrTree tree=NULL;
string s;
s = "ABCDEFG";
CreatBiTree(tree, s, s.length(), 1);
//flr(tree);
InThreading(tree);
InOrderThreading(tree);
}