#include <iostream>
#include <stack>
using namespace std;
typedef struct Node {
int value;
struct Node *left;
struct Node *right;
}Node, *ptrNode;
class BinaryTree {
private:
ptrNode tree;
public:
void init();
bool isEmpty();
void add(int value);
void traverse();
};
void BinaryTree::traverse() {
if (!isEmpty()) {
stack<ptrNode> s;
ptrNode p = tree;
while(p || !s.empty()) {
if ( p != NULL) {
if (p->left != NULL) {
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;
}
}
}
}
void BinaryTree::init() {
tree = NULL;
}
bool BinaryTree::isEmpty() {
if (tree == NULL)
return true;
return false;
}
void BinaryTree::add(int value) {
ptrNode ptr = new Node();
ptr->value = value;
ptr->left = NULL;
ptr->right = NULL;
if (isEmpty()) {
tree = ptr;
} else {
ptrNode *p = &tree;
while (*p != NULL && (*p)->value != value) {
if (value < (*p)->value) {
p = &(*p)->left;
} else {
p = &(*p)->right;
}
}
if (*p == NULL) {
*p = ptr;
}
}
}
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->traverse();
return 0;
}
二叉查找(排序)树
最新推荐文章于 2022-04-25 21:17:35 发布