0

次のアルゴリズムに従って、配列ベースの「バイナリ検索ツリー」を構築しようとしています。

http://highered.mcgraw-hill.com/olcweb/cgi/pluginpop.cgi?it=gif::600::388::/sites/dl/free/0070131511/25327/tree_insert.gif::TREE-INSERT .

...アルゴリズムを使用して、次のコードを思いつきました:

void BST::insert( const data &aData )
{
     item *y = &items[root_index];   // Algorithm calls for NULL assignment..
     item *x = &items[root_index]; 

while ( ! items[root_index].empty )
{
    y->theData = x->theData; // Ptrs are required or else a crash occurs.
    if ( aData < x->theData )
    {
        x->leftChild = aData;
    }
    else
    {
        x->rightChild = items[root_index].theData;
    } 

    // what is p[z] = y? is it outside the looping scheme?

    root_index++; // and make the new child the root?   
}
    if ( y->empty ) 
    {
        items[root_index].theData = aData;
        items[root_index].empty = false;
    }
    else if ( aData < y->theData )
    {
        y->leftChild = aData; 
    // If we already have a left/right child...make it the root? re-cmpr?
              }
    else
    {
        y->rightChild = items[root_index].theData;
    }

  }

質問:

p[z] <- y の意味がわかりません....トラバースを模倣するためにルートをインクリメントしているだけです。

すでに左/右の子がいる場合、ルートを上書きしようとしている左/右の子を作成する必要がありますか? そこで、元のルート「R」に戻るように再帰的にする必要がありますか?

挿入 insert("R"); 挿入 ("A"); 挿入 ("F"); 挿入 ("L"); 挿入 ("B"); 挿入 ("C"); 挿入 ("T");

4

1 に答える 1

1

私の推測では、if/else ステートメントが正しく比較されていません。

aData->getName() < items[root_index].theData

なぜしないのですか

(*aData) < items[root_index].theData

??

getName メソッドは、比較を機能させるために、基本的にオブジェクトのコピーを返す必要があります。

BST 用に作成した Insert メソッドを次に示します。

    /* Insert by node */
    template<class T>
    void Tree<T>::Insert(Node<T> *insertingNode)
    {
        Node<T> *y = NULL;
        Node<T> *x = &this->Root;

        while( x != NULL)
        {
            // y is used as a temp
            y = x;

            // given value less than current
            if(insertingNode->value < x->value)
            {
                // move to left of current
                x = x->ptrLeft;
            }
            else
            {
                // move to right of current
                x = x->ptrRight;
            }
        }

        // now, we're in place
        // parent of inserting value is last node of loop
        insertingNode->ptrParent = y;

        // if there is no node here, insert the root
        if (y == NULL)
        {
            Root = *insertingNode;
        }
        else
        {
            // Place inserting value accordingly
            if(insertingNode->value < y->value)
            {
                // Goes on the left
                y->ptrLeft = insertingNode;
            }
            else
            {
                // Goes on the right
                y->ptrRight = insertingNode;
            }
        }

    };
于 2009-11-14T04:22:10.300 に答える