只要 item 较小并因此插入到左侧,我的函数就可以工作,但是当它应该向右插入时,似乎什么也没有发生。它不会崩溃或其他任何事情,它只是不执行插入操作。
我不明白这是怎么发生的,因为在这两种情况下,代码中唯一的不同是单词 left 或 right(据我所知)。对于更有经验的人来说有什么明显的吗?
template <typename T>
void BST<T>::insertHelper(BST<T>::BinNodePtr &subRoot, const T& item)
{
BinNode *newNode;
BinNode *parent;
BinNode *child;
newNode = new BinNode;
newNode->data = item;
// newNode->left = NULL;
// newNode->right = NULL;
parent = subRoot;
child = subRoot;
if (!subRoot){
subRoot = newNode;
} else {
if (item < child->data){
child = child->left;
} else if (item > child->data){
child = child->right;
}
while (child){
parent = child;
if (item < child->data){
child = child->left;
} else if (item > child->data){
child = child->right;
}
}
child = newNode;
if (child->data < parent->data)
parent->left = child;
else if (child->data < parent->data)
parent->right = child;
}
}
最佳答案
你最后的'if'和'else if'有相同的条件。第二个应该是'>'
关于C++迭代插入二叉搜索树BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642411/