#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 postTraverse();
void postThreading();
void postOrderTraverse_Thr();
};
void ThreadedBinaryTree::postOrderTraverse_Thr() {
ptrNode p = tree;
stack<int> result;
while (p != head) {
result.push(p->value);
if (p->rTag == Link) {
p = p->right;
} else {
p = p->left;
}
}
while(!result.empty()) {
std::cout << result.top() << " ";
result.pop();
}
std::cout << std::endl;
}
void ThreadedBinaryTree::postThreading() {
head = new Node();
if (tree) {
head->lTag = Link;
head->left = tree;
} else {
head->lTag = Thread;
head->left = head;
}
head->rTag = Thread;
head->right = tree;
ptrNode p = head;
ptrNode q = head->left;
stack<ptrNode> s;
while(q || !s.empty()) {
if (q) {
s.push(q);
if (q->right) {
q->rTag = Link;
p = q;
q = q->right;
} else {
q->rTag = Thread;
q->right = p;
p = q;
q = NULL;
}
} else {
q = s.top()->left;
s.pop();
if (p->left) {
p->lTag = Link;
} else {
p->lTag = Thread;
p->left = q;
}
}
}
p->lTag = Thread;
p->left = head;
}
void ThreadedBinaryTree::postTraverse() {
ptrNode p = tree;
stack<ptrNode> s;
stack<int> result;
while(p || !s.empty()) {
if (p) {
result.push(p->value);
s.push(p);
p = p->right;
} else {
p = s.top()->left;
s.pop();
}
}
while (!result.empty()) {
std::cout << result.top() << " ";
result.pop();
}
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;
}
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->postTraverse();
tbt->postThreading();
tbt->postOrderTraverse_Thr();
delete tbt;
return 0;
}
后序遍历二叉树: 37 35 51 47 58 73 93 99 88 62
遍历后序线索二叉树:37 35 51 47 58 73 93 99 88 62