题目
二叉树的深度
一、深度优先搜索 dfs
一棵二叉树的最大深度,一定是:
max(左子树的最大深度+1, 右子树的最大深度+1)
根据这个规律,可以写出如下递归求解的代码~
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
max_depth_left, max_depth_right = 1, 1
if root.left:
max_depth_left = self.maxDepth(root.left) + 1
if root.right:
max_depth_right = self.maxDepth(root.right) + 1
return max(max_depth_left, max_depth_right)
一、广度优先搜索(bfs)
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth_2(self, root):
'''bfs'''
if not root:
return 0
res, tmp = 1, []
queue = [root]
while queue:
node = queue.pop(-1)
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
if not queue and tmp:
queue = tmp
tmp = []
res += 1
return res