二叉查找树
2015-08-08 15:17
260 查看
二叉树的一个重要的应用是他们在查找中的应用假设树中的每一个结点存储一项数据。使二叉树成为二叉查找树的性质是,对于树中的每个结点X,它的左子树中所有项的值小于X中的项,而它的右子树中所有项的值大于X中的项。注意,这意味着,该树所有死亡元素都可以用某一种一致的方式排序。
template <typename Comparable> class BinarySearchTree { public: BinarySearchTree(); BinarySearchTree(const BinarySearchTree & rhs); ~BinarySearchTree(); const Comparable & findMin() const; const Comparable & findMax() const; bool contains( cpnst Comparable &x )const; bool isEmpty( ) const; void printTree() const; void makeEmpty( ); void insert( const Comparable &x ); void remove( const Comparable &x ); const BinarySearchTree & operator=(const BinarySearchTree & rhs); private: struct BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode( const Comparable & theElementmBinaryNode* lt,BinaryNode * rt):element(theElement),left(lt),right(rt){} }; BinaryNode *root; void insert(const Comparable &x, BinaryNode * &t )const; void remove( const Comparable & x,BinaryNode * & t) const; BinaryNode * findsMin( BinaryNode* t) const; BinaryNode * findMax( BinaryNoode* t) const; bool contains (const Comparable & x, BinaryNode *t) const; void makeEmpty(BinaryNode *t); void printTree(BinaryNode *t ) constl BinaryNode * clone( BinaryNode *t) conbst; };
二叉查找树类的框架
contains方法
如果在树T中有项为X的结点,那么contain操作就返回true,否则,若没有这样的结点就返回false。树结构使得该操作很简单。如果T为空,那么就可以返回false:否则,如果存在存在X就返回true。若以上两种情况都不成立,就对T的一个子树进行递归调用。至于是左子树还是右子树取决于X与存储在T中的项的关系。
/** *Return true if x is found in the tree. */ bool contains( const Comparable & x ) const { return contains(x,root); } /** *Insert x into the tree; duplicates are ignored. */ void insert( const Comparable & x) { insert(x,root); } /** * Remove x from the tree. Nothing is done if x is not found. * / void remove( const Comparable & x) { remove(x,root); } /** *Internal method to test if an item is in a subtree. * x is item to search for. * * t is the node that roots the subtree. * / bool contains(const Comparable * x, BinaryNode *t ) const { if( t== NULL) return false; else if ( x< t->element) return contains(x,t->left); else if( t->element < x ) return contains(x,t->right); else return true; //Match } 注意测试的顺序。关键的问题是首先要对是否为空树进行测试,因为如果不这么做就会产生一个企图通过NULL指针访问数据成员的运行错误。其余的测试应该使得最不可能的情况安排在最后进行。还要注意,这里的两个递归调用事实上都尾递归并且可以通过一个while循环很容易代替。尾递归的使用在这里是合理的,因为算法表达式的简明性是以速度的降低为代价的,而这里所使用的栈空间的量也只不过是O(logN)而已。
相关文章推荐
- 二叉查找树
- AVL树-自平衡二叉查找树(Java实现)
- 二叉查找树的插入,删除,查找
- 二叉树数据结构
- 二叉查找数的C++实现
- 二叉查找树--插入、删除、查找
- Binary Search Tree
- 二叉查找树
- 数据结构(scheme) -- 抽象数据类型(ADT) -- 二叉查找树
- 数据结构之二叉查找树
- 二叉查找树
- 二叉查找树(二叉排序树、有序二叉树)算法分析及实现
- 二叉查找树
- 二叉查找树
- 二叉查找树的C语言实现
- LeetCode | Unique Binary Search Trees II
- LeetCode | Unique Binary Search Trees
- 算法导论 第十二章:二叉查找树(Binary Search Trees)
- 树 - 数据结构 (二叉查找树、AVL树)
- 【数据结构】二叉查找树