#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef struct Node {
int value;
struct Node * left;
struct Node * right;
}Node, *ptrNode;
class BinaryTree {
private:
ptrNode tree;
public:
void init();
void add(int value);
bool search(int value, ptrNode *&ptr);
void inOrderTraverse();
void preOrderTraverse();
void postOrderTraverse();
void levelOrderTraverse();
};
void BinaryTree::levelOrderTraverse() {
ptrNode ptr;
queue<ptrNode> q;
q.push(tree);
while(!q.empty()) {
ptr = q.front();
q.pop();
if (ptr) {
std::cout << ptr->value << " ";
q.push(ptr->left);
q.push(ptr->right);
}
}
std::cout << std::endl;
}
void BinaryTree::postOrderTraverse() {
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();
s.pop();
p = p->left;
}
}
while(!result.empty()) {
std::cout << result.top() << " ";
result.pop();
}
std::cout << std::endl;
}
void BinaryTree::preOrderTraverse() {
ptrNode p = tree;
stack<ptrNode> s;
while (p || !s.empty()) {
if (p) {
std::cout << p->value << " ";
s.push(p->right);
p = p->left;
} else {
p = s.top();
s.pop();
}
}
std::cout << std::endl;
}
void BinaryTree::inOrderTraverse() {
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 BinaryTree::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 BinaryTree::search(int value, ptrNode *&ptr) {
ptr = &tree; // 这里要注意,不是*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 BinaryTree::init() {
tree = NULL;
}
int main() {
BinaryTree *bt = new BinaryTree();
bt->init();
bt->add(62);
bt->add(88);
bt->add(58);
bt->add(47);
bt->add(35);
bt->add(73);
bt->add(51);
bt->add(99);
bt->add(37);
bt->add(93);
bt->inOrderTraverse();
bt->preOrderTraverse();
bt->postOrderTraverse();
bt->levelOrderTraverse();
delete bt;
return 0;
}
运行结果:
中序:35 37 47 51 58 62 73 88 93 99
前序:62 58 47 35 37 51 88 73 99 93
后序:37 35 51 47 58 73 93 99 88 62
层序:62 58 88 47 73 99 35 51 93 37