更新每个树行中找最大值Java实现

This commit is contained in:
wutianjue
2022-03-07 14:38:03 +08:00
committed by GitHub
parent a27d1a454d
commit b79f3e0fb7

View File

@ -1300,23 +1300,23 @@ java代码
```java ```java
class Solution { class Solution {
public List<Integer> largestValues(TreeNode root) { public List<Integer> largestValues(TreeNode root) {
List<Integer> retVal = new ArrayList<Integer>(); if(root == null){
Queue<TreeNode> tmpQueue = new LinkedList<TreeNode>(); return Collections.emptyList();
if (root != null) tmpQueue.add(root); }
List<Integer> result = new ArrayList();
while (tmpQueue.size() != 0){ Queue<TreeNode> queue = new LinkedList();
int size = tmpQueue.size(); queue.offer(root);
List<Integer> lvlVals = new ArrayList<Integer>(); while(!queue.isEmpty()){
for (int index = 0; index < size; index++){ int max = Integer.MIN_VALUE;
TreeNode node = tmpQueue.poll(); for(int i = queue.size(); i > 0; i--){
lvlVals.add(node.val); TreeNode node = queue.poll();
if (node.left != null) tmpQueue.add(node.left); max = Math.max(max, node.val);
if (node.right != null) tmpQueue.add(node.right); if(node.left != null) queue.offer(node.left);
} if(node.right != null) queue.offer(node.right);
retVal.add(Collections.max(lvlVals)); }
} result.add(max);
}
return retVal; return result;
} }
} }
``` ```