思路:
// @Title: 在每个树行中找最大值 (Find Largest Value in Each Tree Row)
// @Author: qisiii
// @Date: 2024-09-14 23:34:00
// @Runtime: 3 ms
// @Memory: 44.2 MB
// @comment:
// @flag:
/**
* 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> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
Integer max=Integer.MIN_VALUE;
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
max=Math.max(max,node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
result.add(max);
}
return result;
}
}