Skip to content

Commit b79f3e0

Browse files
authored
更新每个树行中找最大值Java实现
1 parent a27d1a4 commit b79f3e0

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
@@ -1300,23 +1300,23 @@ java代码:
13001300
```java
13011301
class Solution {
13021302
public List<Integer> largestValues(TreeNode root) {
1303-
List<Integer> retVal = new ArrayList<Integer>();
1304-
Queue<TreeNode> tmpQueue = new LinkedList<TreeNode>();
1305-
if (root != null) tmpQueue.add(root);
1306-
1307-
while (tmpQueue.size() != 0){
1308-
int size = tmpQueue.size();
1309-
List<Integer> lvlVals = new ArrayList<Integer>();
1310-
for (int index = 0; index < size; index++){
1311-
TreeNode node = tmpQueue.poll();
1312-
lvlVals.add(node.val);
1313-
if (node.left != null) tmpQueue.add(node.left);
1314-
if (node.right != null) tmpQueue.add(node.right);
1315-
}
1316-
retVal.add(Collections.max(lvlVals));
1317-
}
1318-
1319-
return retVal;
1303+
if(root == null){
1304+
return Collections.emptyList();
1305+
}
1306+
List<Integer> result = new ArrayList();
1307+
Queue<TreeNode> queue = new LinkedList();
1308+
queue.offer(root);
1309+
while(!queue.isEmpty()){
1310+
int max = Integer.MIN_VALUE;
1311+
for(int i = queue.size(); i > 0; i--){
1312+
TreeNode node = queue.poll();
1313+
max = Math.max(max, node.val);
1314+
if(node.left != null) queue.offer(node.left);
1315+
if(node.right != null) queue.offer(node.right);
1316+
}
1317+
result.add(max);
1318+
}
1319+
return result;
13201320
}
13211321
}
13221322
```

0 commit comments

Comments
 (0)