515. 在每个树行中找最大值https://leetcode.cn/problems/find-largest-value-in-each-tree-row/515. 在每个树行中找最大值
难度中等264
给定一棵二叉树的根节点 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
通过次数93,765提交次数141,491
/**
* 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) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<Integer> ans = new ArrayList<>();
if(root!=null) queue.offer(root);
while(!queue.isEmpty())
{
int size = queue.size();
int max =Integer.MIN_VALUE;
for(int i=0;i<size;i++)
{
TreeNode node = queue.poll();
max = max>node.val?max:node.val;
if(node.right!=null) queue.add(node.right);
if(node.left!=null) queue.add(node.left);
}
ans.add(max);
}
return ans;
}
}