[英]C++ iterative insert into binary search tree BST
只要项目较小并因此插入左侧,我的功能就会起作用,但是当它应该向右移动时,似乎没有任何事情发生。 它没有崩溃或任何东西,它只是没有插入。
我不明白这是怎么发生的,因为在任何一种情况下代码中唯一不同的是左边或右边的单词(据我所见)。 有经验的人有什么明显的东西吗?
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'具有相同的条件。 第二个应该是'>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.