我无法让preView300
功能正常工作。我知道算法工作正常,因为我已经看到其他例子完全相同的方式。我相信我的findMaxNode/removeNode
功能。我尝试将不同的指针传递给我的findMaxNode
函数,但没有任何正确的。
例如:
我按此顺序插入这些数字,8,4,12,2,6,10,14,20
并调用删除功能删除8
。我得到了这个输出6,4,2,12,10,14,20
。我知道findMaxNode
正在尝试做的是摆脱8
并将其替换为20并删除包含20的节点并将所有内容连接起来。
如果我能就这个过程无效的原因得到一些帮助,请告诉我。如果我必须在这篇文章中添加任何内容以帮助您,请告诉我。
结构定义:
typedef float Element300;
struct TreeNode300;
typedef TreeNode300 * TreePtr300;
struct TreeNode300
{
Element300 element;
TreePtr300 left;
TreePtr300 right;
};
删除功能:
void BST300::remove300(const Element300 element, TreePtr300 & root)
{
if(root == NULL)
{
cerr << "Error: Remove Failed!" << endl;
}
else if(element == root->element )
{
removeNode300(root);
}
else if(element < root->element)
{
remove300(element, root->left);
}
else
{
remove300(element, root->right);
}
return;
}
删除节点功能:
void BST300::removeNode300(TreePtr300 & root)
{
TreePtr300 tempPointer = NULL;
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
else if(root->right == NULL)
{
tempPointer = root;
root = root->left;
tempPointer->left = NULL;
delete tempPointer;
}
else if(root->left == NULL)
{
tempPointer = root;
root = root->right;
tempPointer->right = NULL;
delete tempPointer;
}
else
{
findMaxNode300(root->right, tempPointer);
root->element = tempPointer->element;
delete tempPointer;
}
tempPointer = NULL;
return;
}
找到最大值函数:
void BST300::findMaxNode300(TreePtr300 & root, TreePtr300 & tempPointer)
{
if(root->right == NULL)
{
tempPointer = root;
root = root->left;
tempPointer->left = NULL;
}
else
{
findMaxNode300(root->right, tempPointer);
}
return;
}
inView:
void BST300::inView300(const TreePtr300 root)const
{
if(root)
{
inView300(root->left);
cout << root->element << "-> ";
inView300(root->right);
}
return;
}
预览:
void BST300::preView300(const TreePtr300 root) const
{
if(root)
{
cout << root->element << "-> ";
preView300(root->left);
preView300(root->right);
}
return;
}
结果:
PREVIEW
------------------------------------------------------
Begin -> 20-> 4-> 2-> 6-> 12-> 10-> 14-> End
INVIEW
------------------------------------------------------
Begin -> 2-> 4-> 6-> 20-> 10-> 12-> 14-> End
预期结果:
PREVIEW
------------------------------------------------------
Begin -> 20-> 4-> 2-> 6-> 12-> 10-> 14-> End
INVIEW
------------------------------------------------------
Begin -> 2.0-> 4.0-> 6-> 10-> 12-> 14-> 20 -> End
二进制搜索树原文:
8
4 12
2 6 10 14
- 20
预期:
20
4 12
2 6 10 14
答案 0 :(得分:0)
removeNode300
功能中的逻辑不正确。删除具有两个子节点的节点时,将要删除的元素替换为该分支中的最大元素,并删除最旧的节点。以树的概念为例:
5
3 7
2 4 6 8
从树中删除5
然后使其看起来像:
8
3 7
2 4 6 -
七不超过八,所以事情在这里崩溃了。
您可以将要删除的节点替换为左侧最大的节点,也可以替换右侧的最低节点。您可以通过更改findMaxNode300
中removeNode300
的来电,轻松解决此问题。改为通过root->left
:
void BST300::removeNode300(TreePtr300 & root)
{
if(root->left == NULL && root->right == NULL) {}
else
{
findMaxNode300(root->left, tempPointer); //this line
}
}
显然保留了其余的代码,我只是将其删除以使其更简洁。