思路
原题链接
- 每一层维护一个变量,用于存储最大值
- 注意:q.poll() 语句要在for循环内部执行
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new LinkedList<>();
if (root == null) {
return result;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int sz = q.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
max = Math.max(max, cur.val);
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
result.add(max);
}
return result;
}
}
|