Leetcode 450. Delete Node in a BST 删除BST中的节点 解题报告

1 解题思想

现在有一个二叉搜索树,现在要让你删除一个节点,并且保证整个BST的性质不变。

要保证整个性质,我们必须在删除的位置上,找一个合适的值来进行替换,使得BST上的每个节点都满足 当前节点的值大于左节点但是小于右节点

而替换策略就是:
1、当前删除位置,用左边子树的最大值的节点替换
2、或者是,用右边子树的最小值的节点替换

用上面的策略就可以保证删除后性质不变,并且调整开销也很少

2 原题

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).

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

3 AC解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int findReplacement(TreeNode parent,TreeNode node,boolean isLeft){
        if(node.right == null){
            if (isLeft)
                parent.left = node.left;
            else parent.right = node.left;
            return node.val;
        }
        return findReplacement(node,node.right,false);
    }
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null)
            return null;
        if(root.val == key){
            if(root.left == null)
                return root.right;
            if(root.right == null)
                return root.left;
            root.val = findReplacement(root,root.left,true); // 选择左边最大的,或者右边最小的
        } else{
            if(root.val > key)
                root.left = deleteNode(root.left,key);
            else
                root.right = deleteNode(root.right,key);
        }
        return root;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值