这道题让我们求一棵树的每层的最大值,我们用深度优先遍历遍历树的每一层找到最大值就可以了。
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int max = Integer.MIN_VALUE;
int size = q.size();
for (int i = 0; i < size; 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);
}
res.add(max);
}
return res;
}