class Solution {
public List largestValues(TreeNode root) {
//为了避免队列中的节点混淆,分别使用两个计数器来记录当前队列中当前层节点的个数和下一层节点的个数
int current = 0;
int next = 0;
Queue queue = new linkedList<>();
int max = Integer.MIN_VALUE;
if(root != null){
queue.offer(root);
current = 1;
}
//使用动态数组来存储结果
ArrayList result = new ArrayList<>();
//层次遍历二叉树
while(!queue.isEmpty()){
//遍历每一层的节点遍历时需要减去当前成的计数器,计入子节点时需要加上下一层节点的个数
TreeNode node = queue.poll();
if(max < node.val){
max = node.val;
}
current--;
if(node.left != null){
queue.offer(node.left);
next++;
}
if(node.right != null){
queue.offer(node.right);
next++;
}
//m当每层遍历结束时需要对计数器和结果重新处理
if(current == 0){
current = next;
next = 0;
result.add(max);
max = Integer.MIN_VALUE;
}
}
return result;
}
}