104 Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

1. Question

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

2. Implementation

(1) DFS
1
class Solution {
2
public int maxDepth(TreeNode root) {
3
if (root == null) {
4
return 0;
5
}
6
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
7
}
8
}
Copied!
(2) BFS
1
class Solution {
2
public int maxDepth(TreeNode root) {
3
if (root == null) {
4
return 0;
5
}
6
7
Queue<TreeNode> queue = new LinkedList<>();
8
queue.add(root);
9
int size = 0, depth = 0;
10
11
while (!queue.isEmpty()) {
12
size = queue.size();
13
++depth;
14
15
for (int i = 0; i < size; i++) {
16
TreeNode curNode = queue.remove();
17
18
if (curNode.left != null) {
19
queue.add(curNode.left);
20
}
21
22
if (curNode.right != null) {
23
queue.add(curNode.right);
24
}
25
}
26
}
27
return depth;
28
}
29
}
Copied!

3. Time & Space Complexity

DFS: 时间复杂度:O(n), 空间复杂度O(h)
BFS: 时间复杂度:O(n), 空间复杂度O(w), w为一层中有最多node的个数