二叉查找樹

二叉樹的一個重要的應用是他們在查找中的應用假設樹中的每一個結點存儲一項數據。使二叉樹成爲二叉查找樹的性質是,對於樹中的每個結點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)而已。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章