友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

104. 二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

0104 01
输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。

  • -100 <= Node.val <= 100

思路分析

后根遍历,当然也可以使用BFS遍历。

0104 01
  • 一刷

  • 二刷

  • 三刷

  • 四刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * Runtime: 1 ms, faster than 14.28% of Java online submissions for Maximum Depth of Binary Tree.
 *
 * Memory Usage: 40.7 MB, less than 5.38% of Java online submissions for Maximum Depth of Binary Tree.
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-01-24 22:17
 */
public int maxDepth(TreeNode root) {
    if (Objects.isNull(root)) {
        return 0;
    }
    int left = 0;
    if (Objects.nonNull(root.left)) {
        left = maxDepth(root.left);
    }
    int right = 0;
    if (Objects.nonNull(root.right)) {
        right = maxDepth(root.right);
    }
    return Math.max(left, right) + 1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
 * 后根遍历既可以访问父节点,又可以从返回值中获取想要的信息,
 * 比如深度,子节点等等。
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-06-30 22:09:09
 */
public int maxDepth(TreeNode root) {
  if (root == null) {
    return 0;
  }
  int left = maxDepth(root.left);
  int right = maxDepth(root.right);
  return Math.max(left, right) + 1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-09-20 23:45:16
 */
public int maxDepth(TreeNode root) {
  if (root == null) {
    return 0;
  }
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-11-12 21:49:21
 */
public int maxDepth(TreeNode root) {
  if (null == root) {
    return 0;
  }
  int left = maxDepth(root.left);
  int right = maxDepth(root.right);
  return Math.max(left, right) + 1;
}

思考题:尝试使用迭代方式来解决一下。