#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; }
二叉查找(排序)树——递归查找
最新推荐文章于 2021-12-15 20:56:21 发布