【发布时间】:2016-02-28 10:05:39
【问题描述】:
有什么方法可以对 Bst 和 Avl 树使用相同的插入函数?问题是 Bst 和 Avl 有不同的节点类型,但我不想让 Bst 节点成为一般情况(里面有 height 和 Node* 父级,这是没有意义的,因为 a 内不需要父级和高度Bst)。
class Bst
{
public:
struct Node
{
int value;
Node* left;
Node* right;
};
Node* insert(Node* node) {/* do stuff using Bst::Node */}
// ...
};
class Avl : public Bst
{
public:
struct Node : public Bst::Node
{
int height;
Node* parent;
};
// now I want that Bst::insert use this Node
// instead of the old one
Node* insert(Node* node)
{
Node* inserted_node = Bst::insert(node);
/* rotations stuff */
return inserted_node;
}
};
我想做的大致是Bst::Node "virtual"。
那么,如何解决实现Avl Tree的问题,而不需要仅仅因为Node改变而重写整个insert函数呢?
【问题讨论】:
-
为什么BST和AVL树的节点类型不同?据我了解,表示的数据是一样的,AVL树只是使用更复杂的算法来插入和删除节点。
-
这是模板和
virtual是实现同一目标的两种不同机制的情况之一。但在这种特定情况下,virtual显然是劣势。它不是通常的风格选择,而是一个好/坏的选择。 -
BST 只需要一个值和左右指针,AVL 需要一个额外的高度值和父指针。表示的数据(值)是同一类型
-
我不相信有足够的共同点值得分享该代码的麻烦。但是,如果您选择这样做,它可以通过几种不同的方式实现。最强大的方法是使用 CRTP,这样基类(其中定义了 insert)可以使用派生类的内部类型(例如
Node)。
标签: c++ inheritance binary-search-tree avl-tree