[Leetcode-Tree]Delete Node in a BST

发布时间:2019-06-24 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[Leetcode-Tree]Delete Node in a BST脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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:

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
  1. 解题思路

我们可以用递归来查找Key,在找到需要删除的节点后,我们需要分情况讨论:
1) 节点是叶子节点,直接返回null;
2) 节点有一个孩子,直接返回孩子;
3)节点有两个孩子,我们要将右子树中最小的节点值赋值给根节点,并在右子树中删除掉那个最小的节点。

2.代码

public class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null) return root;
        if(key>root.val)
            root.right=deleteNode(root.right,key);
        else if(key<root.val)
            root.left=deleteNode(root.left,key);
        else{
            if(root.left!=null&&root.right!=null){
                root.val=findMin(root.right).val;
                root.right=deleteNode(root.right,root.val);
            }
            else{
                if(root.left==null)
                    root=root.right;
                else root=root.left;
            }
        }
        return root;
    }
    private TreeNode findMin(TreeNode root){
        TreeNode node=root;
        while(node.left!=null)
            node=node.left;
        return node;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[Leetcode-Tree]Delete Node in a BST全部内容,希望文章能够帮你解决[Leetcode-Tree]Delete Node in a BST所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: