zoukankan      html  css  js  c++  java
  • 0450. Delete Node in a BST (M)

    Delete Node in a BST (M)

    题目

    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. 如果 key<root.val,向左递归;
    2. 如果 key>root.val,向右递归;
    3. 如果 key==root.val,分为3中情况:
      1. root没有左子树,那么直接返回root的右子树;
      2. root没有右子树,那么直接返回root的左子树;
      3. root既有左子树又有右子树,那么在root的右子树中找到最小的值,即右子树中最左侧的结点,将它的值赋给root,再删掉这个结点(即上述没有左子树的情况)。也可以找root左子树中最大(最右侧)的结点。

    代码实现

    Java

    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return null;
            }
    
            if (key < root.val) {
                root.left = deleteNode(root.left, key);
            } else if (key > root.val) {
                root.right = deleteNode(root.right, key);
            } else if (root.left == null) {
                root = root.right;
            } else if (root.right == null) {
                root = root.left;
            } else {
                TreeNode cur = root.right;
                TreeNode pre = root;
                while (cur.left != null) {
                    cur = cur.left;
                    pre = pre == root ? root.right : pre.left;
                }
                root.val = cur.val;
                if (pre == root) {
                    pre.right = cur.right;
                } else {
                    pre.left = cur.right;
                }
            }
    
            return root;
        }
    }
    
  • 相关阅读:
    如何了解网络链路的性能,吞吐量测试
    Struts+Spring+HibernateSSH整合实例
    在百度贴吧打出被和谐的字和特殊字符:比如繁体字
    SVN 小记
    SVN 小记
    SVN needslock 设置强制只读属性
    在百度贴吧打出被和谐的字和特殊字符:比如繁体字
    TortoiseSVN与Subversion 1.5
    .NET中非对称加密RSA算法的密钥保存
    SVN needslock 设置强制只读属性
  • 原文地址:https://www.cnblogs.com/mapoos/p/13591525.html
Copyright © 2011-2022 走看看