目录
用递归和广度优先搜索(BFS)实现二叉树的最大深度
递归:自底向上(比较容易理解)
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def depth(root):
if not root:
return 0
return max(depth(root.left), depth(root.right)) + 1
return depth(root)
递归:自顶向下
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def up_down(root, depth):
if not root:
return depth
return max(up_down(root.left, depth+1), up_down(root.right, depth+1))
return up_down(root, 0)
广度优先搜索,思路与二叉树的层序遍历相同
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# BFS
from collections import deque
if not root:
return 0
queue, depth = deque([root]), 0
while queue:
depth += 1
n = len(queue)
for _ in range(n):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth