[LeetCode] Problem 515 - Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.

Example

Input:

1
2
3
4
5
    1
/ \
3 2
/ \ \
5 3 9

Output: [1, 3, 9]

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();

if (root == null)
return result;

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

while (!queue.isEmpty()) {
int size = queue.size();
int max = Integer.MIN_VALUE;

for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
max = Math.max(max, node.val);

if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}

result.add(max);
}

return result;
}