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 回答