二叉树654|617|700|98

654最大二叉树

# 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 constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums) == 1:
            root = TreeNode(nums[0])
            return root

        max_val = 0
        max_val_index = 0
        for i in range(len(nums)):
            if nums[i] > max_val:
                max_val = nums[i]
                max_val_index = i
        root = TreeNode(max_val)
        if max_val_index > 0:
            left = nums[:max_val_index]
            root.left = self.constructMaximumBinaryTree(left)
        if max_val_index < len(nums) - 1:
            right = nums[max_val_index + 1:]
            root.right = self.constructMaximumBinaryTree(right)
        return root

617合并二叉树

# 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 mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root1:
            root1 = root2
            return root1
        if not root2:
            return root1
        
        root1.val += root2.val
        root1.left = self.mergeTrees(root1.left, root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)
        return root1

700二叉搜索树中的搜索

# 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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root or root.val == val:
            return root
        result = None
        if val < root.val:
            result = self.searchBST(root.left, val)
        if val >root.val:
            result = self.searchBST(root.right, val)

        return result

98验证二叉搜索树

# 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 __init__(self):
        self.min_val = float('-inf')
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        
        left = self.isValidBST(root.left)
        if self.min_val < root.val:
            self.min_val = root.val
        else:
            return False
        right = self.isValidBST(root.right)
        return left and right

全部评论

相关推荐

码农索隆:单休一个月少休息4天,一年就是48天,平时节假日,别人3天假期,单休的两天
点赞 评论 收藏
分享
水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务