资讯专栏INFORMATION COLUMN

[LeetCode] 450. Delete Node in a BST

spacewander / 1486人阅读

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;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72000.html

相关文章

  • leetcode450. Delete Node in a BST

    摘要:题目要求假设有一棵二叉搜索树,现在要求从二叉搜索树中删除指定值,使得删除后的结果依然是一棵二叉搜索树。思路和代码二叉搜索树的特点是,对于树中的任何一个节点,一定满足大于其所有左子节点值,小于所有其右子节点值。 题目要求 Given a root node reference of a BST and a key, delete the node with the given key i...

    yzd 评论0 收藏0
  • leetcode 315 Count of Smaller Numbers After Self 以

    摘要:题目意思就是要一个个的返回当前的最小值。所以解法自然就是。我们需要找出被打乱的点并返回正确结果。然后将两个不正确的点记录下来,最后回原来正确的值。如果是叶子节点,或者只有一个子树。思想来自于的代码实现。 跳过总结请点这里:https://segmentfault.com/a/11... BST最明显的特点就是root.left.val < root.val < root.right.v...

    inapt 评论0 收藏0
  • [Leetcode-Tree]Delete Node in a BST

    摘要:解题思路我们可以用递归来查找,在找到需要删除的节点后,我们需要分情况讨论节点是叶子节点,直接返回节点有一个孩子,直接返回孩子节点有两个孩子,我们要将右子树中最小的节点值赋值给根节点,并在右子树中删除掉那个最小的节点。 Delete Node in a BSTGiven a root node reference of a BST and a key, delete the node w...

    wangjuntytl 评论0 收藏0
  • [Leetcode-Tree] Kth Smallest Element in a BST

    摘要:解题思路本题需要找的是第小的节点值,而二叉搜索树的中序遍历正好是数值从小到大排序的,那么这题就和中序遍历一个情况。 Kth Smallest Element in a BSTGiven a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You ...

    Carl 评论0 收藏0
  • [Leetcode] Kth Smallest Element in a BST 二叉搜索树第k小节

    摘要:中序遍历复杂度时间空间思路因为左节点小于根节点小于右节点,二叉搜索树的一个特性就是中序遍历的结果就是树内节点从小到大顺序输出的结果。这里采用迭代形式,我们就可以在找到第小节点时马上退出。这样我们就可以用二叉树搜索的方法来解决这个问题了。 Kth Smallest Element in a BST Given a binary search tree, write a function...

    Dean 评论0 收藏0

发表评论

0条评论

spacewander

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<