# 104. 二叉树的最大深度
# 题目描述
给定一个二叉树 root,返回其最大深度。最大深度是从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:3
1
2
2
示例 2:
输入:root = [1,null,2]
输出:2
1
2
2
# 思路
最大深度怎么从左右子树得到?代码随想录原题中讲过:根节点的高度就是整棵树的最大深度。后序遍历先得到左右子树的高度,再返回 1 + max(左高度, 右高度)。
递归函数传入当前节点,返回以它为根的树高。空节点高度为 0;单层逻辑依次求左、右高度,再算当前节点高度。这就是递归三部曲。
# 模拟过程
主站用下面这棵树说明深度:
节点 9、15、7 的高度都是 1;节点 20 的高度是 1 + max(1,1) = 2;根节点 3 的高度是 1 + max(1,2) = 3。答案是 3。
# 解题代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
int leftDepth = maxDepth(root->left); // 左
int rightDepth = maxDepth(root->right); // 右
return 1 + max(leftDepth, rightDepth); // 中:根节点的高度
}
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 复杂度分析
- 时间复杂度:O(n),每个节点访问一次。
- 空间复杂度:O(h),h 为树高,最坏退化为 O(n)。
# 其他语言
# Python3
class Solution:
def maxDepth(self, root):
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
1
2
3
4
5
2
3
4
5
# Java
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
1
2
3
4
5
6
2
3
4
5
6
# Go
func maxDepth(root *TreeNode) int {
if root == nil { return 0 }
left, right := maxDepth(root.Left), maxDepth(root.Right)
if left > right { return left + 1 }
return right + 1
}
1
2
3
4
5
6
2
3
4
5
6
# JS
var maxDepth = function(root) {
if (root === null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
};
1
2
3
4
2
3
4
# 与代码随想录联系
104.二叉树的最大深度还介绍了前序求深度和层序遍历两种写法。本题的后序求高度思路也会用在543.二叉树的直径中。
@2021-2026 代码随想录 版权所有
粤ICP备19156078号
评论
验证登录状态...