#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();
bool search(int value, ptrNode *&ptr);
bool remove(int value);
};
bool BinaryTree::remove(int value) {
ptrNode *ptr = NULL;
if (search(value, ptr)) {
ptrNode r = *ptr;
if ((*ptr)->left == NULL) {
*ptr = (*ptr)->right;
} else if ((*ptr)->right == NULL) {
*ptr = (*ptr)->left;
} else {
ptrNode p = r;
ptrNode q = r;
r = p->left;
while (r->right) {
q = r;
r = r->right;
}
p->value = r->value;
if (q != p) {
q->right = r->left;
} else {
q->left = r->left;
}
q->right = r->left;
}
delete r;
return true;
}
return false;
}
bool BinaryTree::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 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;
}
}
std::cout << std::endl;
}
}
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->add(53);
bt->traverse();
bt->remove(47);
bt->traverse();
return 0;
}