【题目】
【代码】
【方法1-递归1】

# 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
class Solution:
def maxDepth(self, root: TreeNode) -> int:
self.maxnum=0
self.depth(root,0)
return self.maxnum
def depth(self,root,d):
if not root:
self.maxnum=max(self.maxnum,d)
return
self.depth(root.left,d+1)
self.depth(root.right,d+1)
【方法2-递归2】

# 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
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
else:
left_depth=self.maxDepth(root.left)+1
right_depth=self.maxDepth(root.right)+1
return max(left_depth,right_depth)
【方法3-BFS】借助队列实现

class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
queue=[root]
depth=0
while queue:
size=len(queue)
for i in range(size):
node=queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth+=1
return depth

本文介绍了三种不同的方法来计算二叉树的最大深度:递归方法1、递归方法2和基于广度优先搜索(BFS)的方法。递归方法通过自顶向下地分解问题,而BFS则使用队列来逐层遍历树结构。
603

被折叠的 条评论
为什么被折叠?



