1

2*i +1私はそれを再帰的にやろうとしましleftChild2*i +2

void BST::insert(const data &aData)
{
    if ( items[Parent].empty ) 
    {
        items[Parent].theData = aData;
        items[Parent].empty = false;
    }
    else if ( aData < items[Parent].theData )
    {
        Parent = 2 * Parent + 1;
        if ( Parent >= maxSize ) this->reallocate();
        this->insert(aData);
    }
    else
    {
        Parent = (2 * rightChild++)+ 2;
        if ( Parent >= maxSize ) this->reallocate();
        this->insert(aData);
    }
}

元の親よりも小さいアイテムを挿入すると正常に機能します...しかし、より大きなものを見つけると、すべてが台無しになります:x

void BST::reallocate()
{
    item *new_array = new item[maxSize*2];

    for ( int array_index = 0; array_index < maxSize; array_index++ ) 
    {
        if ( ! items[array_index].empty )
        {
            new_array[array_index].theData = items[array_index].theData;
        }
    }
    maxSize *= 2;
    delete [] items;

    items = NULL;
    items = new_array;
}

これが私のctorなので、誰も混乱することはありません。

BST::BST(int capacity) : items(new item[capacity]), size(0), Parent(0),
leftChild(0), rightChild(0)
{
    items->empty = true;
    maxSize = capacity;
}
private:
    int size;  // size of the ever growing/expanding tree :)
    int Parent;
    int maxSize;    
    int leftChild;
    int rightChild;
    struct item
    {
        bool empty;
        data theData;
    };
    item *items;    // The tree array

上記の挿入機能は、実際に私が得ることができる最高のものです..

                                 R
                                / \
                               /   \
                              /     \
                             L       X
                            / \     / \
                           J   V   K   T   <--The only out of place node.
                          / \   \
                         / NULL  \
                        G        /
                                P

挿入時:R, L, J, G, X, K, V, P, Tその順

4

1 に答える 1

1

あなたの問題はこの行にあると思います:

    Parent = (2 * rightChild++)+ 2;

なぜここで代わりに rightChild を使用しているの(2 * Parent) + 2ですか?

より明確にするために、インデックスを指定して、左/右の子と親のインデックスを計算するために、いくつかの単純なインライン関数をクラスに追加することができます。

inline int getLeftChildIndex(int nodeNdx) { return (nodeNdx * 2) + 1; }
inline int getRightChildIndex(int nodeNdx) { ... }
inline int getParentIndex(int nodeNdx) { ... }

新しいノードを挿入する場所を決定するために、クラスsearch()またはfind()メソッド (あると仮定します) を使用することを検討することもできます。検索関数は、既存のノードのインデックス (重複する値の挿入を処理する方法を決定するのはユーザー次第です) または新しい値を挿入する場所のインデックスのいずれかを返す必要があります。

于 2009-11-24T00:08:38.093 に答える