可比较的类和二叉搜索树

Comparable Class and Binary Search Tree

本文关键字:搜索树 可比较      更新时间:2023-10-16

我需要创建一个抽象的'可比'类。从此类继承的任何类都将实现 compare_to 方法。

/* returns 1 if this class > rhs, 0 if equal, -1 if this class < rhs */    
int compare_to(const Comparable& rhs);

创建一个二叉搜索树类,该类存储"可比较"对象而不是整数。

我遇到的问题是理解二叉搜索树类的外观以及我们如何在其中存储可比较的对象。

我们可以使用模板。

不要这样做,不要做任何通用界面。这有很多缺点。如果从 IComparable 派生的两个类不能相互比较 - 如 Int 和 String,该怎么办?

你说你可以使用模板。使用它们 - 并提供比较器作为第二个模板参数:

template <class T, class Comparator>
class BSTree  {
public:
   bool present(const T& value)
   {
       int res = comparator(value, root->value);
       switch(res) {
         case 0: return true;
         case -1: return find(root->left, value);
         case 1: return find(root->right, value);
       }
   }
private:
  struct Node {
  ...
  };
  Node* root;
  Comparator comparator;
};

典型的比较器是:

template <class T>
class RawComparator {
public:
    int operator()(const T& l, const T& r) 
    {
       if (l < r) return -1;
       else if (l > r) return 1;
       else return 0;
    }
};

以及您的 int 二叉搜索树:

typedef BSTree<int, RawComparator<int>> BSTreeInt;
我相信

你必须为二叉搜索树创建类模板。类模板将如下所示

template <typename Comparable>
class BSTNode
{
public:
BSTNode const Comparable & theElement = Comparable( ),BSTNode *lt = NULL, BSTNode *rt = NULL);
int size( BSTNode *t ) ;
int height( BSTNode *t);
void printPostorder( ) ; 
void printInOrder( ) ; 
void printPreOrder( ) ;
bool operator<(const Comparable&,const Comparable &); 
BSTNode *duplicate() ;

public:
Comparable element;
BSTNode *left;
BSTNode *right;
};

然后,您可以重载operator<以添加Comparable类型对象的比较方法。