【leetcode刷刷】654.最大二叉树 、617.合并二叉树 、700.二叉搜索树中的搜索 、98.验证二叉搜索树

654. 最大二叉树

  1. 很典型的递归
class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        if len(nums) == 0:
            return 

        max_val = max(nums)
        max_index = nums.index(max_val)
        root = TreeNode(max_val)
        root.left = self.constructMaximumBinaryTree(nums[:max_index])
        root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
        return root     

617. 合并二叉树

  1. 自己写还是递归
  2. 题解里没有新建root,而是利用了root1 : root1.val += root2.val
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        # 两棵树一起,递归?
        if not root1 and not root2:
            return 
        if not root1:
            return root2
        if not root2:
            return root1
        root = TreeNode(root1.val + root2.val)
        root.left = self.mergeTrees(root1.left, root2.left)
        root.right = self.mergeTrees(root1.right, root2.right)
        return root       

700. 二叉搜索树中的搜索

  1. 定义题?哦我写的是迭代,其实递归也可以
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        cur = root
        while(cur):
            # print(cur.val)
            if cur.val == val:
                return cur
            elif cur.val > val:
                cur = cur.left
            else: cur = cur.right
        return 

98. 验证二叉搜索树

  1. 二叉树练完感觉自己只会写递归了…
  2. 哦!中序就是二叉搜索树的顺序,只要中序遍历再判断是不是递增就好了
class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        # 递归,返回bool,需要左右子树的max和min,左子树的max小于当前,右子树的min小于当前
        return self.traversal(root, -float('inf'), float('inf'))

    def traversal(self, root, min_val, max_val):
        if not root:
            return True
        if root.val <= min_val or root.val >= max_val:
            return False
        if not root.left and not root.right:
            return True
        left = self.traversal(root.left, min_val, root.val)
        right = self.traversal(root.right, root.val, max_val)
        return left and right
        

你可能感兴趣的:(leetcode,算法,职场和发展)