• 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;
        }
    }
    
  • 相关阅读:
    Final发布
    Final发布 视频展示
    Final发布 文案+美工展示
    PSP总结报告
    作业 20181204-1 每周例行报告
    对团队成员公开感谢
    作业 20181127-1 附加作业 软件工程原则的应用实例分析
    作业 20181127-2 每周例行报告
    作业 20181120-1 每周例行报告
    作业 20181113-2 每周例行报告
  • 原文地址:https://www.cnblogs.com/mapoos/p/13591525.html
Copyright © 2020-2023  润新知