450 delete a node in a BST

第一部是先遞歸遍歷找到key == root->val;
刪除一個節(jié)點有以下情況:
1,node->right == NULL node->left == NULL
直接刪除
2,node->right 或者node->left其中一個非NULL,另外一個是NULL
直接返回子孩子得地址

3,node->left != NULL && node->right !=NULL
從右子樹里面挑選出最小的來替換掉當前節(jié)點,(右子樹最左邊的節(jié)點),因為這個節(jié)點可以滿足大于所有的左樹和小于所有的右樹

/* Given a binary search tree and a key, this function deletes the key
   and returns the new root */
struct TreeNode* deleteNode(struct TreeNode* root, int key)
{
    // base case
    if (root == NULL) return root;
 
    // If the key to be deleted is smaller than the root's key,
    // then it lies in left subtree
    if (key < root->val)
        root->left = deleteNode(root->left, key);
 
    // If the key to be deleted is greater than the root's key,
    // then it lies in right subtree
    else if (key > root->val)
        root->right = deleteNode(root->right, key);
 
    // if key is same as root's key, then This is the node
    // to be deleted
    else
    {
        // node with only one child or no child
        if (root->left == NULL)
        {
            struct TreeNode *temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL)
        {
            struct TreeNode *temp = root->left;
            free(root);
            return temp;
        }
 
        // node with two children: Get the inorder successor (smallest
        // in the right subtree)

         struct TreeNode *temp ;
         temp = root->right;
         while(temp->left)
            temp = temp->left;
 
        // Copy the inorder successor's content to this node
        root->val = temp->val;
 
        // Delete the inorder successor
        root->right = deleteNode(root->right, temp->val);
    }
    return root;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容