104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/
solution
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
l = self.maxDepth(root.left)
r = self.maxDepth(root.right)
return max(l, r) + 1时间复杂度:O(n) 空间复杂度:O(1)
follow-up
111. Minimum Depth of Binary Tree
BFS
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
level = [root]
depth = 1
while level:
this_level = []
for i in level:
if i.left is None and i.right is None:
return depth
if i.left:
this_level.append(i.left)
if i.right:
this_level.append(i.right)
level = this_level
depth += 1时间复杂度:O(n) 空间复杂度:O(n)
DFS
时间复杂度:O(n) 空间复杂度:O(h)
Last updated