题目
给定一个二叉树 root,返回其最大深度。
二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。

提示
一句话思路:递归——空节点深度为 0,非空节点深度 = 左右子树最大深度 + 1(加上自己这一层)。
- 递归终止条件:节点为空,返回 0。
- 递推关系:
maxDepth(node) = max(maxDepth(node.left), maxDepth(node.right)) + 1。 - 时间 O(n)、空间 O(h),h 为树的高度(递归栈深度)。
答案
python
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: # 空节点,深度为 0
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 # 左右子树最大深度 + 1(自己)
留言板