450 delete a node in a BST

第一部是先递归遍历找到key == root->val;
删除一个节点有以下情况:
1,node->right == NULL node->left == NULL
直接删除
2,node->right 或者node->left其中一个非NULL,另外一个是NULL
直接返回子孩子得地址

3,node->left != NULL && node->right !=NULL
从右子树里面挑选出最小的来替换掉当前节点,(右子树最左边的节点),因为这个节点可以满足大于所有的左树和小于所有的右树

/* 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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容