0%

Leetcode 104 二叉树的最大深度

给定一个二叉树,找出其最大深度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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

# DFS
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def helper(root, depth):
if not root:
return depth
else:
return max(helper(root.left, depth+1), helper(root.right, depth+1))
return helper(root, 0)

# BFS
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
queue, res = [root], 0
while queue:
tmp = []
for node in queue:
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
queue = tmp
res += 1
return res