Poison

104. Maximum Depth of Binary Tree

DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
private static class State {
private int maxDepth;
}

public int maxDepth(TreeNode root) {
State state = new State();
dfs(root, 0, state);
return state.maxDepth;
}

private void dfs(TreeNode root, int depth, State state) {
if (root == null) {
return;
}

state.maxDepth = Math.max(state.maxDepth, ++depth);
dfs(root.left, depth, state);
dfs(root.right, depth, state);
}
}
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
26
27
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}

Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);

int depth = 0;

while (!queue.isEmpty()) {
depth++;
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 depth;
}
}
Reference

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