Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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. 根据BST的特性,找到需要删除的node。
2. 如果node左右子树都是空的,直接返回null。
3. 如果左子树为空,那么直接用右侧子树代替node。
4. 如果右侧子树为空,那么直接用左子树代替node。
5. 如果左右子树都不是空,有些麻烦。首先要去node的右子树中找到最小的那个节点,也就是右子树中最左侧的节点。
然后用它去替代node,并且把node的父节点的left置为空。
递归的时候,什么时候直接return,什么时候root.left = 调用递归,需要值得注意。
这个关系到,总是疑惑,删除本node,那么如何将父节点的left(right)置为null?需要好好理解。
详细可以看二叉查找树的查找、插入和删除 - Java实现
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return root;
        }
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
        } else {
            if (root.right == null) {
                return root.left;
            } else if (root.left == null) {
                return root.right;
            } else {
                TreeNode temp = root;
                root = findMin(root.right);
                root.right = deleteMin(temp.right);
                root.left = temp.left;
            }
        }
        return root;
    }
    
    private TreeNode findMin(TreeNode root) {
        if (root.left != null) {
            return findMin(root.left);
        }
        return root;
    }
    
    private TreeNode deleteMin(TreeNode root) {
        if (root.left != null) {
            root.left = deleteMin(root.left);
        } else {
            return root.right;
        }
        return root;
    }
}

 

posted on 2018-11-16 01:01  NickyYe  阅读(108)  评论(0编辑  收藏  举报