zoukankan      html  css  js  c++  java
  • LeetCode 450. 删除二叉搜索树中的节点

    450. 删除二叉搜索树中的节点

    Difficulty: 中等

    给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 **key **对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。

    一般来说,删除节点可分为两个步骤:

    1. 首先找到需要删除的节点;
    2. 如果找到了,删除它。

    说明: 要求算法时间复杂度为 O(h),h 为树的高度。

    示例:

    root = [5,3,6,2,4,null,7]
    key = 3
    
        5
       / 
      3   6
     /    
    2   4   7
    
    给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。
    
    一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。
    
        5
       / 
      4   6
     /     
    2       7
    
    另一个正确答案是 [5,2,6,null,4,null,7]。
    
        5
       / 
      2   6
          
        4   7
    

    Solution

    Language: ****

    分四种情况讨论,这道题还是有点难度的!

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
            if not root:
                return None
            
            if root.val > key:
                root.left = self.deleteNode(root.left, key)
            elif root.val < key:
                root.right = self.deleteNode(root.right, key)
            else:
                if not root.left:
                    return root.right
                elif not root.right:
                    return root.left
                
                minNode = self.findMin(root.right)
                root.val = minNode.val
                root.right = self.deleteNode(root.right, root.val)
            return root
        
        def findMin(self, root):
            while root.left:
                root = root.left
            return root
    
  • 相关阅读:
    博客地址
    Version 1.4.2_03 of the JVM not suitable for this product.解决
    http请求(一) 工具
    Service 的两种启动方法和区别
    软件开发过程应该采用集中优势兵力各个击破
    架构感悟
    嵌套事务模版
    软件行业对人才的依赖
    使用SQL Server 2005 新的语法ROW_NUMBER()进行分页的两种不同方式的性能比较
    架构设计中的分层与分区
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14094196.html
Copyright © 2011-2022 走看看