给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Deque<TreeNode> q = new LinkedList<>();
q.addLast(root);
while (!q.isEmpty()) {
int size = q.size();
int max = Integer.MIN_VALUE;
while (size -- > 0) {
TreeNode t = q.pollFirst();
max = Math.max(max, t.val);
if (t.left != null) q.addLast(t.left);
if (t.right != null) q.addLast(t.right);
}
res.add(max);
}
return res;
}
}