leetcode刷题记录(hot100)

树:

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: return root2
        if not root2: return root1
        root = TreeNode()
        root.val = root1.val + root2.val
        root.left = self.mergeTrees(root1.left, root2.left)
        root.right = self.mergeTrees(root1.right, root2.right)
        return root
"""
时间复杂度:O(min⁡(m,n))O(\min(m,n))O(min(m,n)),其中 mmm 和 nnn 分别是两个二叉树的节点个数。对两个二叉树同时进行深度优先搜索,只有当两个二叉树中的对应节点都不为空时才会对该节点进行显性合并操作,因此被访问到的节点数不会超过较小的二叉树的节点数。

空间复杂度:O(min⁡(m,n))O(\min(m,n))O(min(m,n)),其中 mmm 和 nnn 分别是两个二叉树的节点个数。空间复杂度取决于递归调用的层数,递归调用的层数不会超过较小的二叉树的最大高度,最坏情况下,二叉树的高度等于节点数。

"""

543. 二叉树的直径

可恶简单题都没做出来!还是没有真正理解递归555

# 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 diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        # 计算左子树和右子树的最大深度
        self.res = 0
        def depth(root):
            if not root: return 0
            l = depth(root.left)
            r = depth(root.right)
            self.res = max(self.res, l+r)
            return max(l, r)+1
        depth(root)
        return self.res

226. 翻转二叉树 简单

104. 二叉树的最大深度 简单

101. 对称二叉树 简单

竟然没想出来

# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(left,right):
            if not (left or right):
                return True
            if not (left and right):
                return False
            if left.val!=right.val:
                return False
            return dfs(left.left,right.right) and dfs(left.right, right.left)
        if not root: return False
        return dfs(root.left, root.right)

94. 二叉树的中序遍历 简单

中等

96. 不同的二叉搜索树

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

 

你可能感兴趣的:(leetcode,算法,深度优先)