二叉查找(排序)树——递归查找

来源:互联网 发布:惠州市房管局网络问政 编辑:程序博客网 时间:2024/06/07 07:34
#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();bool search(int value, ptrNode *&p);bool add(int value);void traverse();};void BinaryTree::traverse() {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;}}}bool BinaryTree::add(int value) {ptrNode ptr = new Node();ptr->value = value;ptr->left = NULL;ptr->right = NULL;ptrNode *p = &tree;if (!search(value, p)) {*p = ptr;return true;}return false;}bool BinaryTree::search(int value, ptrNode *&p) {if (*p == NULL) {return false;} else {if ((*p)->value > value) {p = &(*p)->left;return search(value, p);} else if ((*p)->value < value) {p = &(*p)->right;return search(value, p);} else {return true;}}}void BinaryTree::init() {tree = NULL;}bool BinaryTree::isEmpty() {if (tree == NULL) {return true;}return false;}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;}

0 0