LeetCode104二叉树的最大深度

未经博主同意,禁止瞎JB转载。

LeetCode104二叉树的最大深度

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/

我的解法:

递归:

复杂度分析:

  • 时间复杂度:我们每个结点只访问一次,因此时间复杂度为O(N), 其中 N是结点的数量。

  • 空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 N次(树的高度),因此保持调用栈的存储将是 O(N)。但在最好的情况下(树是完全平衡的),树的高度将是 log(N)。因此,在这种情况下的空间复杂度将是 O(log(N))。

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def maxDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         if root == None:
15             return 0
16         else:
17             return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))

官方解法:

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/

猜你喜欢

转载自www.cnblogs.com/kianqunki/p/9775575.html