forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindLargestValueInEachTreeRow.java
More file actions
43 lines (32 loc) · 995 Bytes
/
FindLargestValueInEachTreeRow.java
File metadata and controls
43 lines (32 loc) · 995 Bytes
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class FindLargestValueInEachTreeRow {
public List<Integer> largestValues(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
Queue<TreeNode> next = new LinkedList<>();
List<Integer> list = new LinkedList<>();
if (root == null) {
return list;
}
queue.offer(root);
int max = Integer.MIN_VALUE;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if (node.left != null) {
next.offer(node.left);
}
if (node.right != null) {
next.offer(node.right);
}
if (queue.isEmpty()) {
list.add(max);
queue.addAll(next);
next.clear();
max = Integer.MIN_VALUE;
}
}
return list;
}
}