二叉查找树

来源:互联网 发布:ios内存清理软件 编辑:程序博客网 时间:2024/05/13 01:16
#ifndef 二叉查找树_H_#define 二叉查找树_H_#include <iostream>  // 在头文件中不要用using namespace std; 容易产生错误,enum Boolean {FALSE,TRUE};template<class Type>class Element{public:Type key;  // key是键值,// 添加更多的数据,};template<class Type> class BST;  // 前置声明,template<class Type>class BstNode   // 树节点,{friend class BST<Type>;//private:public:Element<Type> data;BstNode* LeftChild;BstNode* RightChild;void display(int i);   // display就是显示指针的数据,显示左边的数和右边的数,};template<class Type>class BST{public:BST(BstNode<Type> *init = 0){root = init;}// 要增加Delete// 要增加InOrder/PreOrder/PostOrderBoolean Insert(const Element<Type>& x);  //Insert 是插入,返回值是一个bool值,BstNode<Type>* Search(const Element<Type>& x); // Search就是查找,BstNode<Type>* Search(BstNode<Type>*, const Element<Type>&); // 这个是使用递归进行查找,BstNode<Type>* IterSearch(const Element<Type>&);  // 这个是普通的查找,void display(){cout << "\n";if(root)root->display(1);elsecout << "这是一颗空树\n";}private:BstNode<Type> *root;  // 这个是树的根。};template<class Type>void BstNode<Type>::display(int i){std::cout << "Position: " << i << ", data.key = " << data.key << "\n";if(LeftChild) LeftChild->display(2*i);  // 表示的是下一行的数据,if(RightChild) RightChild->display(2*i+1);}template<class Type>Boolean BST<Type>::Insert(const Element<Type>& x){BstNode<Type> *p = root;BstNode<Type> *q = 0;  // q指向p的父节点,// insert之前要先查找,while(p){q = p;if(x.key == p->data.key) return FALSE;  // 发生重复,失败返回FALSE,if(x.key < p->data.key) p = p->LeftChild;elsep = p->RightChild;}// 找到的位置就是q,p = new BstNode<Type>;p->LeftChild = p->RightChild = 0;p->data = x;if(!root) root = p;else if(x.key < q->data.key) q->LeftChild = p;else q->RightChild = p;return TRUE;}template<class Type>BstNode<Type>* BST<Type>::Search(const Element<Type> &x){return Search(root, x);}template<class Type>BstNode<Type>* BST<Type>::Search(BstNode<Type> *b, const Element<Type> &x){if(!b) return 0;if(x.key == b->data.key) return b;if(x.key < b->data.key) return Search(b->LeftChild,x);return Search(b->RightChild,x);}template<class Type>BstNode<Type>* BST<Type>::IterSearch(const Element<Type> &x){for(BstNode<Type>* t = root; t;){if(x.key == t->data.key) return t;if(x.key < t->data.key)t = t->LeftChild;elset = t->RightChild;}}#endif

#include <iostream>#include "二叉查找树.h"using namespace std;int main(){BST<int> m;Element<int> a,b,c,d,e,f,g,h,i,j;a.key = 5;b.key = 3;c.key = 11;d.key = 3;e.key = 15;f.key = 2;g.key = 8;h.key = 22;i.key = 20;j.key = 9;cout << "\n" << m.Insert(a);  // a 就是5,就是rootcout << endl;m.display();  //输出的是: 位置是1,数据是5,cout << "\n" << m.Insert(b) << endl << endl;cout << m.Insert(c) << endl;cout << m.Insert(d) << endl;cout << m.Insert(e) << endl;cout << m.Insert(f) << endl;cout << m.Insert(g) << endl;cout << m.Insert(h) << endl;cout << m.Insert(i) << endl;m.display();BstNode<int> *p = m.Search(f);cout << "找到的是:" << p->data.key << endl;BstNode<int> *p2 = m.IterSearch(i);cout << "找到的是:" << p2->data.key << endl;return 0;}

0 0
原创粉丝点击