104. Maximum Depth of Binary Tree

DFS

1
2
3
4
5
6
7
8
9
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}

return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}

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
25
class Solution {
public int maxDepth(TreeNode root) {
int maxDepth = 0;

Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.offer(root);
}

while (!queue.isEmpty()) {
maxDepth++;
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}

return maxDepth;
}
}

References

104. Maximum Depth of Binary Tree
剑指 Offer 55 - I. 二叉树的深度