Alex Allain的跳入C ++ 给了我一个非递归地删除二叉搜索树的难以置信的任务(第17章)。我想出了一种通过修改我的结构定义来简化这个任务的方法,以便它包含一个指向父节点的指针,而不仅仅是左右指针。我尽量避免使用堆栈/链表数据结构。
我完成此任务的算法是:
问题在于我陷入无限循环。 我怀疑我的insert()函数有缺陷,但我可能错了。
以下代码包括到目前为止提到的所有功能/结构:
struct node
{
int key_value;
node *p_left;
node *p_right;
node *parent;
};
node* insert (node *p_tree, int key, node* parent)
{
if ( p_tree == NULL )
{
node* p_new_tree = new node;
p_new_tree->p_left = NULL;
p_new_tree->p_right = NULL;
p_new_tree->key_value = key;
p_new_tree->parent = parent;
return p_new_tree;
}
else if( key < p_tree->key_value )
p_tree->p_left = insert( p_tree->p_left, key, p_tree );
else
p_tree->p_right = insert( p_tree->p_right, key, p_tree );
return p_tree;
}
void destroy_tree_Iteratively(node* p_tree)
{
int nodesDestroyed = 0; //checking to see if I delete the right amount
while (p_tree != NULL)
{
if (p_tree->p_left == NULL && p_tree->p_right == NULL)
{
node* placeHolder = p_tree->parent;
delete p_tree;
p_tree = placeHolder;
}
else if (p_tree->p_left != NULL)
p_tree = p_tree->p_left;
else if (p_tree->p_right != NULL)
p_tree = p_tree->p_right;
}
cout << "You've deleted " << nodesDestroyed << " nodes!" << endl;
}
答案 0 :(得分:1)
当您删除节点时,您需要将其指针从父节点归零,无论左右指针指向哪一个。如果有父母。否则,第一个if
测试永远不会成立,并且您将永远继续遍历。