【Leetcode】104 :二叉树的最大深度

 

 题目解析:

利用递归的代码如下:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root==None:
            return 0
        if self.maxDepth(root.left)>self.maxDepth(root.right):
            return self.maxDepth(root.left)+1
        else:
            return self.maxDepth(root.right)+1

我的方法在正常情况下是没问题的,但是要是给出用例太多就会超过时间,因此采用下面这种写法即可:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root==None:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right))+1

【Leetcode】104 :二叉树的最大深度

 

 时间复杂度还是太大了,用时太多,时间复杂度更小的方法之后在补充。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-29
  • 2021-04-12
  • 2021-11-09
  • 2021-09-13
猜你喜欢
  • 2021-08-31
  • 2021-08-31
  • 2021-09-23
  • 2021-11-27
  • 2022-01-25
  • 2021-07-14
  • 2021-09-15
相关资源
相似解决方案