【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
时间复杂度还是太大了,用时太多,时间复杂度更小的方法之后在补充。