#include <iostream>
#include <stack>
using namespace std;
typedef enum {
Link, Thread,
} Tag;
typedef struct Node {
int value;
Tag lTag;
Tag rTag;
struct Node *left;
struct Node *right;
} Node, *ptrNode;
class ThreadedBinaryTree {
private:
ptrNode tree;
ptrNode head;
public:
void init();
bool search(int value, ptrNode *&ptr);
void add(int value);
void traverse();
void inThreading();
void inOrderTraverse_Thr();
void inOrderReverse_Thr();
};
void ThreadedBinaryTree::inOrderReverse_Thr() {
ptrNode p = head->left;
while (p != head) {
while (p->rTag == Link) {
p = p->right;
}
std::cout << p->value << " ";
while (p->lTag == Thread && p->left != head) {
p = p->left;
std::cout << p->value << " ";
}
p = p->left;
}
std::cout << std::endl;
}
void ThreadedBinaryTree::inOrderTraverse_Thr() {
ptrNode p = head->left;
while (p != head) {
while (p->lTag == Link) {
p = p->left;
}
std::cout << p->value << " ";
while (p->rTag == Thread && p->right != head) {
p = p->right;
std::cout << p->value << " ";
}
p = p->right;
}
std::cout << std::endl;
}
void ThreadedBinaryTree::inThreading() {
if (tree) {
head->lTag = Link;
head->left = tree;
} else {
head->lTag = Thread;
head->left = head;
}
ptrNode p = head;
ptrNode q = tree;
stack<ptrNode> s;
while (q || !s.empty()) {
if (q) {
if (q->left) {
s.push(q);
q->lTag = Link;
q = q->left;
} else {
q->lTag = Thread;
q->left = p;
p = q;
q = q->right;
}
} else {
q = s.top();
s.pop();
if (!p->right) {
p->rTag = Thread;
p->right = q;
}
p = q;
q = q->right;
}
}
p->rTag = Thread;
p->right = head;
head->rTag = Thread;
head->right = p;
}
void ThreadedBinaryTree::traverse() {
ptrNode p = tree;
stack<ptrNode> s;
while (p || !s.empty()) {
if (p) {
if (p->left) {
s.push(p);
p = p->left;
} else {
std::cout << p->value << " ";
p = p->right;
}
} else {
p = s.top();
s.pop();
std::cout << p->value << " ";
p = p->right;
}
}
std::cout << std::endl;
}
void ThreadedBinaryTree::add(int value) {
ptrNode *ptr;
if (!search(value, ptr)) {
ptrNode p = new Node();
p->value = value;
p->left = NULL;
p->right = NULL;
*ptr = p;
}
}
bool ThreadedBinaryTree::search(int value, ptrNode *&ptr) {
ptr = &tree;
while (*ptr) {
if (value < (*ptr)->value) {
ptr = &(*ptr)->left;
} else if (value > (*ptr)->value) {
ptr = &(*ptr)->right;
} else {
return true;
}
}
return false;
}
void ThreadedBinaryTree::init() {
tree = NULL;
head = new Node();
}
int main() {
ThreadedBinaryTree *tbt = new ThreadedBinaryTree();
tbt->init();
tbt->add(62);
tbt->add(88);
tbt->add(58);
tbt->add(47);
tbt->add(35);
tbt->add(73);
tbt->add(51);
tbt->add(99);
tbt->add(37);
tbt->add(93);
tbt->traverse();
tbt->inThreading();
tbt->inOrderTraverse_Thr();
tbt->inOrderReverse_Thr();
delete tbt;
return 0;
}
输出结果:
中序遍历二叉树: 35 37 47 51 58 62 73 88 93 99
正向遍历线索二叉树:35 37 47 51 58 62 73 88 93 99
反向遍历线索二叉树:99 93 88 73 62 58 51 47 37 35