二叉查找树

二叉树的一个重要的应用是他们在查找中的应用假设树中的每一个结点存储一项数据。使二叉树成为二叉查找树的性质是,对于树中的每个结点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)而已。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值