-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC515.java
More file actions
42 lines (39 loc) · 1.08 KB
/
LC515.java
File metadata and controls
42 lines (39 loc) · 1.08 KB
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
/*
* LC515
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.swing.tree.TreeNode;
public class LC515 {
public static List<Integer> largestValues(TreeNode root) {
// Storing answer
List<Integer> ans = new ArrayList<>();
// Base case
if (root == null) {
return ans;
}
// Use for BFS
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode cur = q.remove();
// If left of tree will not be null add
if (cur.left != null) {
q.add(cur.left);
}
// If right of tree will not be null add
if (cur.right != null) {
q.add(cur.right);
}
max = Math.max(max, cur.val);
}
ans.add(max);
}
return ans;
}
}