我一直试图用C ++编写二进制搜索树,但我的删除方法有些困难。如果它工作,它基本上会使用inorder遍历来搜索树中一个传递给方法的值的节点,只要它实际存在于一个存在的节点上,就会递归调用它自己 - 如果它已经存在 - 如果有的话不是,那么它会立即返回并允许“一步一步”的方法"在递归中检查它所在的区域,就像正常的顺序遍历一样。问题是,我的if语句检查以查看当前节点是否存在似乎不起作用,总是返回true并使其无限迭代具有合理端点的左分支。以下是我使用的代码:
template<class T>
void binSTree<T>::remove(Node<T>*& nowOn, const T& input)
{
if(nowOn) //This is the part that breaks. My cout statement has proved that by repeating itself an infinite number of times.
{
cout << "So we know it's entering this.";
if(nowOn->left)
remove(nowOn->left, input);
if(nowOn->data == input)
{
if(!(nowOn->left) && !(nowOn->right))
{
delete nowOn;
}
if(nowOn->left && !(nowOn->right))
{
if(!(pred(nowOn)->left->data == input))
pred(nowOn)->left = nowOn->left;
else if(!(pred(nowOn)->right->data == input))
pred(nowOn)->right = nowOn->left;
delete nowOn;
}
if(nowOn->right && !(nowOn->left))
{
if(!(pred(nowOn)->left->data == input))
pred(nowOn)->left = nowOn->right;
else if(!(pred(nowOn)->right->data == input))
pred(nowOn)->right = nowOn->right;
delete nowOn;
}
if(nowOn->left && nowOn->right)
{
if(!(pred(nowOn)->left->data == input))
pred(nowOn)->left = nowOn->right;
else if(!(pred(nowOn)->right->data == input))
pred(nowOn)->right = nowOn->right;
delete nowOn;
}
}
if(nowOn->right)
remove(nowOn->right, input);
}
else
{
return;
}
return;
}
pred
方法是一个简单的非递归堆栈,它遍历整个树,以查找左或右节点是输入节点的内容。这已经过测试,效果很好。至于节点,这里是代码:
template < class T > class binTree; // forward declaration
template < class T > class binSTree; // forward declaration
template < class T > class Node {
friend class binTree < T >; // binTree is friend
friend class binSTree < T >; // binSTree is friend
public:
// default constructor
Node ( const T& x = T ( ), Node < T >* l = 0, Node < T >* r = 0 ) :
data ( x ), left ( l ), right ( r ) { }
private:
T data; // data component
Node < T > *left, *right; // left and right links
};
binTree是一个不能删除的二叉树,但它有自己的insert,height,size和inorder遍历方法。 binSTree是具有remove
方法的类,是binTree的派生类。我合理地确定错误来自于我尝试使用if语句检查Node<T>*&
,*&
部分,但我无法弄清楚如何做任何事情关于它。有人有什么想法吗?