我试图通过以下算法构建基于“二进制搜索树”的数组:
...使用算法我提出了以下代码:
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]&lt; - y的含义....我只是递增根来模仿遍历。
如果我已经有一个左/右孩子,那么我应该让那个左/右孩子即将覆盖根?在那里我应该让它重新调整,以便它将切换回原始的根“R”?
的插入 插入( “R”); 插入( “A”); 插入( “F”); 插入( “L”); 插入( “B”); 插入( “C”); 插入( “T”);
答案 0 :(得分: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;
}
}
};