-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindLargestValueInEachTreeRow.java
43 lines (36 loc) · 1.18 KB
/
FindLargestValueInEachTreeRow.java
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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.*;
// https://leetcode.com/problems/find-largest-value-in-each-tree-row/
public class FindLargestValueInEachTreeRow {
private final TreeNode input;
public FindLargestValueInEachTreeRow(TreeNode input) {
this.input = input;
}
public List<Integer> solution() {
if (input == null) {
return Collections.emptyList();
}
List<Integer> result = new ArrayList<>();
Queue<TreeNode> nodes = new LinkedList<>();
nodes.add(input);
while (!nodes.isEmpty()) {
int size = nodes.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode node = nodes.poll();
if (node.val > max) {
max = node.val;
}
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
nodes.add(node.right);
}
}
result.add(max);
}
return result;
}
}