Skip to content

Commit c1bb0d5

Browse files
authored
Update Find Largest Value in Each Tree Row.java
1 parent e68120e commit c1bb0d5

File tree

1 file changed

+28
-22
lines changed

1 file changed

+28
-22
lines changed

Medium/Find Largest Value in Each Tree Row.java

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,38 @@
44
* int val;
55
* TreeNode left;
66
* TreeNode right;
7-
* TreeNode(int x) { val = x; }
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
814
* }
915
*/
1016
class Solution {
11-
public List<Integer> largestValues(TreeNode root) {
12-
List<Integer> list = new ArrayList<>();
13-
if (root == null) {
14-
return list;
15-
}
16-
Queue<TreeNode> queue = new LinkedList<>();
17-
queue.add(root);
18-
while (!queue.isEmpty()) {
19-
int maxVal = Integer.MIN_VALUE;
20-
int size = queue.size();
21-
while (size-- > 0) {
22-
TreeNode removed = queue.remove();
23-
maxVal = Math.max(maxVal, removed.val);
24-
if (removed.left != null) {
25-
queue.add(removed.left);
17+
public List<Integer> largestValues(TreeNode root) {
18+
if (root == null) {
19+
return new ArrayList<>();
2620
}
27-
if (removed.right != null) {
28-
queue.add(removed.right);
21+
List<Integer> result = new ArrayList<>();
22+
Queue<TreeNode> queue = new LinkedList<>();
23+
queue.add(root);
24+
while (!queue.isEmpty()) {
25+
int size = queue.size();
26+
int maxValue = queue.peek().val;
27+
while (size-- > 0) {
28+
TreeNode removed = queue.remove();
29+
maxValue = Math.max(maxValue, removed.val);
30+
if (removed.left != null) {
31+
queue.add(removed.left);
32+
}
33+
if (removed.right != null) {
34+
queue.add(removed.right);
35+
}
36+
}
37+
result.add(maxValue);
2938
}
30-
}
31-
list.add(maxVal);
39+
return result;
3240
}
33-
return list;
34-
}
3541
}

0 commit comments

Comments
 (0)