基本上,该程序由一个 BST 类组成,该类指向二叉树的第一个节点,并且节点也是它们自己的类。
BST 调用这个成员函数:
void remove(const T& x)
{
removeNode(m_root, x);
return;
}
这是删除节点的递归部分,它一直运行到完成:
template <typename T>
void removeNode(TreeNode<T>* &p, const T& x)
{
if(p == NULL)
return;
if(x < p -> m_data)
removeNode(p -> m_left, x);
else if(x > p -> m_data)
removeNode(p -> m_right, x);
else
{
TreeNode<T>* tmp = new TreeNode<T>;
if(p -> m_left == NULL)
{
tmp = p -> m_right;
delete p;
p = tmp;
}
else if(p -> m_right == NULL)
{
tmp = p -> m_left;
delete p;
p = tmp;
}
else
{
tmp = p -> m_right;
TreeNode<T>* tmp2 = new TreeNode<T>;
while(tmp -> m_left != NULL)
{
tmp2 = tmp;
tmp = tmp -> m_left;
}
p -> m_data = tmp -> m_data;
if(tmp2 != NULL)
removeNode(tmp2 -> m_left, tmp -> m_left -> m_data);
else
removeNode(p -> m_right, p -> m_right -> m_data);
}
}
return;
}
当 remove() 函数返回时,我出现了段错误,我想知道为什么?