[leetcode] 450. Delete Node in a BST 解题报告

题目链接: https://leetcode.com/problems/delete-node-in-a-bst/

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

  1. Search for a node to remove.
  2. If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7

思路: 刚开始考虑用迭代来做, 发现非常麻烦, 因为使用迭代的话删除那个节点之后还需要重新连接其父节点指针, 也就是需要记录父节点. 这样的话就变得很麻烦, 因为还有一些特殊的情况, 比如要删除的节点是根节点, 或者还需要记录当前节点是父节点的左子树还是右子树. 

在此时递归就体现了其优越性, 因为递归是可以回溯的, 所以不需要记录父节点. 然后考虑删除以后节点的替换. 有四种替换方式:

1. 如果要删除的节点有左孩子, 则可以直接让左孩子替换其位置, 并且让左孩子的右子树连接到要删除节点的右孩子的最左端

2. 如果要删除的节点有右孩子, 则可以让右孩子替换其位置, 并且让右孩子的左子树连接到要删除节点的左孩子的最右端

3. 如果要删除的节点有左孩子, 则可以取左孩子的最右节点替换要删除的节点

4. 如果要删除的节点有右孩子, 则可以去右孩子的最左节点替换要删除的节点.

在这里我采用的第二种解法.

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(!root) return root;
        if(root->val > key){
            root->left = deleteNode(root->left, key);
            return root;
        }
        else if(root->val < key){
            root->right = deleteNode(root->right, key);
            return root;
        }
        TreeNode* left = root->left, *right = root->right, *tem = left;
        delete root;
        if(!left || !right) return left?left: right;
        while(tem->right) tem = tem->right;
        tem->right = right->left, right->left = left;
        return right;
    }
};


你可能感兴趣的:(leetcode,binary,search,tree)