代码附解释
解决这道题的首要就是必须先理解层序遍历,在层序遍历的基础上加上判断什么时候是进入下一行的,解决了这两个问题就可以很快的实现代码,下面的代码已经做出了详细的解释。
题解:
public static List<Integer> largestValues(TreeNode root){
List<Integer> result = new LinkedList<>();
int now = 1;//当层剩余元素
int next = 0;//记录下一行元素数量
int max = root.val;//记录当前层的当前最大值
if(root==null)return null;
Queue<TreeNode> queue = new LinkedList<>();//用于层序遍历
queue.add(root);
while (!queue.isEmpty()) {
root = queue.poll();//取出当前队列的队首
int t = root.val;
max = Math.max(max, t);//和之前的最大值比较
if (root.left != null) {//判断左节点是否为null,若不为null,则让下一层的元素数量+1
queue.add(root.left);
next++;
}
if (root.right != null) {//判断右节点是否为null,若不为null,则让下一层的元素数量+1
queue.add(root.right);
next++;
}
now--;//处理了当前层的1个元素,所以要当前层未处理数量减1
if (now == 0) {//如果当前层,元素数量为0,那么说明当前层已经处理完毕
now = next;//进入下一层处理,将下一层的数量赋值到now
next = 0;//下一层数量重置
result.add(max);//将记录的这一层的最大值添加到队列
if(!queue.isEmpty()) max = queue.peek().val;//如果队列不为空,就将当前最大值设置为下一层的第一个数
}
}
return result;
}