二叉查找树的简单模板实现
2012-06-24 15:39
435 查看
二叉排序树又称二叉查找树,是一种的高效的查找数据结构,查找效率等同二分法。
以下是二叉查找树的一种简单模板实现:
以下是二叉查找树的一种简单模板实现:
#include <iostream> using namespace std; template <typename T> class BinSearchTree{ public: typedef Node* tree; BinSearchTree():rp(NULL), n(){} ~BinSearchTree(){ _clear(); n = 0; } void insert(const T& d){ _insert(rp, new Node(d)); ++n; } int high()const{ return _high(rp); } tree& find(const T& d){ return _find(rp, d); } void travel()const{ _travel(rp); cout << endl; } bool empty(){ return rp == NULL; } int size(){ return n; } const T& root(){ if(empty()) throw "empty"; return rp->data; } void update(const T& old_data, const T& new_data){ if(remove(old_data)) insert(new_data); } bool remove(const T& d){ tree& t = find(d); if(t == NULL) return false; Node* p = t; if(t->L != NULL) insert(t->R, t->L); t = t->R; delete p; --n; return true; } void clear(){ _clear(rp); } private: struct Node{ T data; Node* L; Node* R; Node(T d):data(d), L(), R(){} Node(T d, Node* l, Node* r):data(d), L(l), R(r){} }; Node* rp;//root pointer int n;//节点个数 /***************以下为工具函数,供接口方法调用**********************/ //向BST中插入节点 void _insert(tree& t, Node* p){ if(t == NULL) t = p; else if(p->data < t->data) insert(t->L, p); else insert(t->R, p); } //找到对应的节点,并返回指向该节点指针的引用 Node*& _find(tree& t, const T& d){ if(t->data == d || t == NULL) return t; else if(d < t->data) return _find(t->L, d); else return _find(t->R, d); } //遍历BST void _travel(const tree& t)const{ if(t != NULL){ _travel(t->L); cout << t->data << ' '; _travel(t->R); } } //clear BST void _clear(tree& t){ if(t != NULL){ _clear(t->L); _clear(t->R); delete t; t = NULL; } } //求BST的高度 int _high(tree& t)const{ if(t == NULL) return 0; int lh = _high(t->L); int rh = _high(t->R); return 1 + ((lh > rh) ? lh : rh); } }; int main() { BinSearchTree<int> bst; bst.insert(2); bst.insert(6); bst.insert(1); bst.travel(); cout << "high:" << bst.high() << endl; bst.update(2, 3); bst.travel(); return 0; }
相关文章推荐
- 二叉查找树的简单模板实现
- 简单数据结构实现——二叉查找树
- java 数据结构 二叉查找树的简单实现
- dotNet中ArrayList的C++模板简单实现
- 二叉查找树简单实现
- c++ 链表(模板)简单实现
- C++模板实现二叉查找树(一 树的数据结构定义与节点插入)
- LintCode_二叉查找树中搜索区间_简单的递归实现
- Java实现的一个简单的模板渲染
- 二叉查找树简单实现
- c++模板重载之字符串模板库的简单实现
- hash表 拉链法 仿sgi stl 非模板简单实现
- 字符串作为freemarker模板的简单实现例子
- 简单的前端渲染模板实现
- 简单模板排序的实现(回顾排序)
- 中级JavaScript例子, 如何实现一个简单实用的模板套用机制, GXTemplate , 第2章(估计要写9章)
- 字符串作为freemarker模板的简单实现例子
- 【原创】javascript模板引擎的简单实现
- 二叉查找树的简单实现
- C++模板实现的简单单链表