二叉查找树的简单C++实现
2014-07-30 23:42
393 查看
#pragma once template <typename Comparable> class BinarySearchTree { public: BinarySearchTree(); BinarySearchTree(const BinarySearchTree &rhs); ~BinarySearchTree() { makeEmpty(); } const Comparable &findMin() const; const Comparable &findMax() const; bool contains(const Comparable &x) const { return contains(x,root); } bool isEmpty() const; void printTree() const; void makeEmpty(); void insert(const Comparable &x) { insert(x,root); } void remove(const Comparable &x) { remove(x,root); } const BinarySearchTree & operator= (const BinarySearchTree &rhs) { if(this != &rhs) { makeEmpty(); root = clone(rhs.root); } reuturn *this; } private: struct BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode(const Comparable & theElement,BinaryNode *lt,BinaryNode *rt) :element(theElement),left(lt),right(rt){ } }; BinaryNode *root; void insert(const Comparable &x,BinaryNode *&t)const { if(t==NULL) t = new BinaryNode(x,NULL,NULL); else if(x<t->element) insert(x,t->left); else if(t->element<x) insert(x,t->right); else ; } void remove(const Comparable &x,BinaryNode *&t)const { if(t == NULL) return; if(x<t->element) remove(x,t->left); else if(t->element < x) remove(x,t->right); else if(t->left != NULL && t->right != NULL) { t->element = findMin(t->right)->element; remove(t->element,t->right); } else { BinaryNode *oldNode = t; t = (t->left != NULL) ? t->left:t->right; delete oldNode; } } BinaryNode * findMin(BinaryNode *t)const { if(t==NULL) return NULL; if(t->left ==NULL) return t; return findMin(t->left); } BinaryNode * findMax(BinaryNode *t)const { if(t != NULL) while(t->right != NULL) t = t->right; return t; } bool contains(const Comparable &x,BinaryNode *t)const { if(t == NULL) return false; else if(x<t->element) return contains(x,x->left); else if(t->element<x) return contains(x,t->right); else return true; } void makeEmpty(BinaryNode *&t) { if(t != NULL) { makeEmpty(t->left); makeEmpty(t->right); delete t; } t = NULL; } void printTree(BinaryNode *t)const { if(t != NULL) { //printf(t->element); printTree(t->left); printTree(t->right); } } BinaryNode * clone(BinaryNode *t)const { if(t == NULL) return NULL; return new BinaryNode(t->element,clone(t->left),clone(t->right)); } };
相关文章推荐
- 用C++实现简单的文件I/O操作
- 标准纯C++实现简单的词法分析器(一)
- c++ stl list 迭代器简单实现
- 一个简单的多叉树C++实现
- 单链表赋值,定位,添加,(C++ ) 简单实现 未整理
- C++ : 用proxy Class实现简单的二维数组。
- c++ 控制台模式下实现的简单进度条
- C++中简单实现foreach循环
- 实例学MFC(3)--超简单C++实现网络下载器
- 策略模式与简单工厂的C++实现
- 标准纯C++实现简单的词法分析器(一)
- 标准纯C++实现简单的词法分析器(三)
- 标准纯C++实现简单的词法分析器(三)
- C++实现的变种二分查找法(折半查找)--二叉查找树
- 用C++实现简单的文件I/O操作
- 用C++实现简单的文件I/O操作
- 标准纯C++实现简单的词法分析器(二)
- 用C++实现简单的文件I/O操作(ifstream,ofstream)
- 堆栈的简单C++实现
- C++ 简单实现委托