Skip to content

Commit 62e4681

Browse files
Merge pull request #1148 from gowsp/patch-1
更新每个树行中找最大值Java实现
2 parents 79b2453 + b79f3e0 commit 62e4681

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

problems/0102.二叉树的层序遍历.md

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,23 +1287,23 @@ java代码:
12871287
```java
12881288
class Solution {
12891289
public List<Integer> largestValues(TreeNode root) {
1290-
List<Integer> retVal = new ArrayList<Integer>();
1291-
Queue<TreeNode> tmpQueue = new LinkedList<TreeNode>();
1292-
if (root != null) tmpQueue.add(root);
1293-
1294-
while (tmpQueue.size() != 0){
1295-
int size = tmpQueue.size();
1296-
List<Integer> lvlVals = new ArrayList<Integer>();
1297-
for (int index = 0; index < size; index++){
1298-
TreeNode node = tmpQueue.poll();
1299-
lvlVals.add(node.val);
1300-
if (node.left != null) tmpQueue.add(node.left);
1301-
if (node.right != null) tmpQueue.add(node.right);
1302-
}
1303-
retVal.add(Collections.max(lvlVals));
1304-
}
1305-
1306-
return retVal;
1290+
if(root == null){
1291+
return Collections.emptyList();
1292+
}
1293+
List<Integer> result = new ArrayList();
1294+
Queue<TreeNode> queue = new LinkedList();
1295+
queue.offer(root);
1296+
while(!queue.isEmpty()){
1297+
int max = Integer.MIN_VALUE;
1298+
for(int i = queue.size(); i > 0; i--){
1299+
TreeNode node = queue.poll();
1300+
max = Math.max(max, node.val);
1301+
if(node.left != null) queue.offer(node.left);
1302+
if(node.right != null) queue.offer(node.right);
1303+
}
1304+
result.add(max);
1305+
}
1306+
return result;
13071307
}
13081308
}
13091309
```

0 commit comments

Comments
 (0)