我正在尝试使用指针在c ++中实现一个简单的二叉树。
我已经成功实现了插入和遍历,但是当我尝试删除节点时遇到了一些问题:
我的主要功能是:
main(){
node* root=createNode(1);
root->left=createNode(2);
root->right=createNode(3);
root->left->left=createNode(4);
root->left->right=createNode(5);
root->right->left=createNode(6);
root->right->right=createNode(7);
inorder(root);
//till here it works fine
delete root->left->left; //problem starts here
cout<<"\n";
inorder(root); //exception is thrown here...
return 0;
} `
inorder函数是非常基本的递归函数:
void inorder(node* root){
if(root!=NULL){
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
有人能告诉我删除行有什么问题吗?
答案 0 :(得分:2)
在delete
之后,尝试访问已删除的指针将导致此问题。您可能想要添加
root->left->left = 0
删除行后。
答案 1 :(得分:0)
您必须将root->left->left
指针设置为NULL
,即它指向什么
在你的代码中
main()
{
node* root=createNode(1);
root->left=createNode(2);
root->right=createNode(3);
root->left->left=createNode(4);
root->left->right=createNode(5);
root->right->left=createNode(6);
root->right->right=createNode(7);
inorder(root);
//Now, Complete program will work
delete root->left->left = 0; //problem solved
cout<<"\n";
inorder(root); // Do you still face any problem ?
return 0;
}
答案 2 :(得分:0)
删除节点后,需要将父节点的左指针重置为零。 不这样做会导致不可预测的结果,具体取决于内存管理的实现方式。有些系统对引用释放内存的引用有异常
答案 3 :(得分:0)
Your trying to delete node which has not null nodes in both right and left side, so you to delete node like this ..
/* deletes a node from the binary search tree */
void delete ( struct btreenode **root, int num )
{
int found ;
struct btreenode *parent, *x, *xsucc ;
/* if tree is empty */
if ( *root == NULL )
{
printf ( "\nTree is empty" ) ;
return ;
}
parent = x = NULL ;
/* call to search function to find the node to be deleted */
search ( root, num, &parent, &x, &found ) ;
/* if the node to deleted is not found */
if ( found == FALSE )
{
printf ( "\nData to be deleted, not found" ) ;
return ;
}
/* if the node to be deleted has two children */
if ( x -> leftchild != NULL && x -> rightchild != NULL )
{
parent = x ;
xsucc = x -> rightchild ;
while ( xsucc -> leftchild != NULL )
{
parent = xsucc ;
xsucc = xsucc -> leftchild ;
}
x -> data = xsucc -> data ;
x = xsucc ;
}
/* if the node to be deleted has no child */
if ( x -> leftchild == NULL && x -> rightchild == NULL )
{
if ( parent -> rightchild == x )
parent -> rightchild = NULL ;
else
parent -> leftchild = NULL ;
free ( x ) ;
return ;
}
/* if the node to be deleted has only rightchild */
if ( x -> leftchild == NULL && x -> rightchild != NULL )
{
if ( parent -> leftchild == x )
parent -> leftchild = x -> rightchild ;
else
parent -> rightchild = x -> rightchild ;
free ( x ) ;
return ;
}
/* if the node to be deleted has only left child */
if ( x -> leftchild != NULL && x -> rightchild == NULL )
{
if ( parent -> leftchild == x )
parent -> leftchild = x -> leftchild ;
else
parent -> rightchild = x -> leftchild ;
free ( x ) ;
return ;
}
}