删除是在函数内部发生的,但在从函数返回后没有反映在 head 中 . 我正在使用双指针,所以我认为应该 .

Code

void delete(node **head,int key)
{
    int x;
    node *p=*head,*q=*head;
    while(p->data!=key)
    {
        q=p; //q will have the address of parent
        if(p->data>key)
            p=p->left;
        else
            p=p->right;
    }   
    if(p->left==NULL && p->right==NULL) //leaf
    {   
        p=NULL;
        return ;
    }
    if(p->left==NULL)
    {
        if(q->left&&q->left==p) //Check if the node to be deleted is a left/right child of parent
        {
            q->left=p->right;
            free(p);
            return;
        }
        if(q->right&&q->right==p)
        {
            q->right=p->right;
            free(p);
            return;
        }

    }
    if(p->left!=NULL && p->right!=NULL)
    {
        q=giveAddress(*head,inorderSuccessor(*head,key));   //give address find the address of the inorder successor
        p->data=q->data;
        free(q);
    }   




}

函数调用:delete(&head,key);

注意:我不明白的一件事是,如果我改变上面函数的叶子部分内的条件,它适用于叶子 .

if(p->left==NULL && p->right==NULL) //leaf
    {   
        if(q->left&&q->left==p) //Check if the node to be deleted is a left/right child of parent
        {
            q->left=NULL;
            free(p);
            return;
        }
        if(q->right&&q->right==p)
        {
            q->right=NULL;
            free(p);
            return;
        }

    }

没关系,因为我们将父指针(左,右)设为NULL . 所以它会删除节点 . 它不会释放内存位置,对吗?

Correct me if I'm wrong

因此,如果我们执行 p=Null ,它会为p分配一个空值,而parent-> left仍然保留要删除的节点的地址 . 因此,它不会被删除 . 只有指针p改变了,休息没问题!

但是,在递归中我们可以这样做......为什么?