[LeetCode] 450. Delete Node in a BST

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

PRoblem

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

Solution

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

脚本宝典总结

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

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

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