LeetCode104-二叉树的最大深度

LeetCode104-二叉树的最大深度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int deep = 1;
queue.offer(root);
int levelSize = 1;
while (!queue.isEmpty()) {
TreeNode poll = queue.poll();
levelSize--;
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
if (levelSize==0){
levelSize = queue.size();
deep++;
}
}
return deep;
}