BM28. [二叉树的最大深度]

https://www.nowcoder.com/exam/oj?tab=%E7%AE%97%E6%B3%95%E7%AF%87&topicId=295
BM28. 二叉树的最大深度
题目分析
求二叉树的最大深度,不就是从下向上求层数吗?所以二叉树的最大深度不就是后序遍历吗?
- 先求左右子树的深度
- 那个深度更深保留哪一个作为深度
- 然后向上处理
完整代码
private int maxDepth(TreeNode root) {
if (root == null)
return 0;
int l= maxDepth(root.left);
int r=maxDepth(root.right);
// 后序遍历来了
int max = Math.max(l, r) + 1;
return max;
}
- 时间复杂度:
,后续遍历二叉树
- 空间复杂度:
,没有使用额外的空间


查看23道真题和解析