2-3树以及如何构建构造函数

2-3 tree and how to build the constructor

本文关键字:构建 构造函数 何构建      更新时间:2023-10-16

我正在尝试为2-3树构建构造函数。但我不知道该怎么做。我们是创建一个从一开始就只有一个值和两个指针(左和中)与该节点关联的节点,还是创建一个有两个值和三个指针(右、中和左)的节点?

这是我的2-3节点类

template<class E>
class BNode
{
public:
    // I'm not sure if this is quite enough for the constructor
    BNode() {_right == nullptr;};
    typedef struct Entry
    {
        E value;
        BNode<E>* _left;
        // Constructor for the entry
        Entry();
    };
    E fValue() {return _first.value;}
    E sValue() {return _second.value;}
    BNode<E>* fLeft() {return _first._left;}
    BNode<E>* sLeft() {return _second._left;}
    //check if the node is 2 or 3 pointers
    bool IsThree() 
    {
        if(_first._left != nullptr && _second._left != nullptr
            && _second._right != nullptr)
            _three = true;
        else
            _three = false;
        return _three;
    }
    Entry fEntry() {return _first;}
    Entry sEntry() {return _second;}
    BNode<E>* right() {return _right;}
private:
    bool _three;
    Entry _first, _second;
    BNode<E>* _right;
};
template<class E>
BNode<E>::Entry::Entry()
{
    _left = nullptr;
}

我认为您应该首先以这种方式声明树:

template<class E>
class BTree
{
public:
    BTree();
    ~BTree();
    class BNode
    {
    public:
        // I'm not sure if this is quite enough for the constructor
        BNode() {_right == nullptr;};
        typedef struct Entry
        {
            E value;
            BNode<E>* _left;
            // Constructor for the entry
            Entry();
        };
        E fValue() {return _first.value;}
        E sValue() {return _second.value;}
        BNode<E>* fLeft() {return _first._left;}
        BNode<E>* sLeft() {return _second._left;}
        //check if the node is 2 or 3 pointers
        bool IsThree() 
        {
            if(_first._left != nullptr && _second._left != nullptr
                && _second._right != nullptr)
                _three = true;
            else
                _three = false;
            return _three;
        }
        Entry fEntry() {return _first;}
        Entry sEntry() {return _second;}
        BNode<E>* right() {return _right;}
    private:
        bool _three;
        Entry _first, _second;
        BNode<E>* _right;
    };
private:
    BNode* root_;
};
template<class E>
BTree<E>::BNode<E>::Entry::Entry()
{
    _left = nullptr;
}

然后,如果使用C++11,BNode()应该包含叶上的一个或两个元素,BTree()应该包含一个列表或/和一个初始化器列表,其中包含每个叶上的对象列表(2或3个对象?)。您应该根据以下图纸从根开始构建树,直到最右下的叶子:http://en.wikipedia.org/wiki/2%E2%80%933_tree