法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;
}
}
}
448



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



