法1:DFS
Python
# 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: Optional[TreeNode]) -> int:
if not root:
return 0
else:
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
Java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return 1;
} else {
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
}
该博客围绕104.二叉树的最大深度问题,介绍了使用DFS(深度优先搜索)的解法,还分别给出了Python和Java两种编程语言的实现。

2252

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



