LeetCode104-二叉树的最大深度

题目链接

英文链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/

中文链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

题目详述

给定一个二叉树,找出其最大深度。

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

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回它的最大深度 3 。

题目详解

  • 若根结点为 null,则树的深度为 0。
  • 若根结点不为 null,则树的最大深度为 1 加上它的左子树和右子树的最大深度的最大值。
1
2
3
4
5
6
7
8
9
public class LeetCode_00104 {

public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}

上面是 DFS 做法,并且是递归形式,也可以改为迭代形式,思路是一致的。

同样,也可以运用 BFS,像层次遍历那样,每进入一层,深度就加一。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class LeetCode_00104 {

public int maxDepth(TreeNode root) {
int res = 0;
Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
++res;
int size = queue.size();
while (size-- != 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return res;
}
}