Delete_node_in_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:
Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).

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. 如果要删除的节点左右子树都存在的话,正如上面所示的其实有两种解决方案,一种就是拿右子树的最小值去替代,另外一种就是拿左子树的最大值去替代。替代完之后又要删除替代的那个节点(这里逻辑就可以套用1去解决)。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    /**
    * 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 NULL;
    //搜索那个要删除的节点
    if(key < root->val){
    //在左子树搜
    root->left = deleteNode(root->left,key);
    } else if(key > root->val){
    //在右子树搜
    root->right = deleteNode(root->right,key);

    } else {
    //找到删除节点,而且左右子树只存在一个以下。
    if(!root->left||!root->right){
    root = (root->left) ? root->left : root->right;
    }else{
    //左右子树都存在
    TreeNode* cur;
    cur = root->right;
    while(cur->left){
    cur = cur->left ;
    }
    root->val = cur->val;
    //删除右子树下用来替换的节点。
    root->right = deleteNode(root->right,cur->val);
    }
    }
    return root;
    }
    };

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×