Leetcode 515. 在每个树行中找最大值
题目链接
https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/description/
题目描述
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
题解
按层次遍历二叉树,计算每层的最大值即可。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) { return list; }
LinkedList<TreeNode> queue = new LinkedList<>();
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();
if (node.val > max) { max = node.val; }
if (node.left != null) { queue.offer(node.left); }
if (node.right != null) { queue.offer(node.right); }
}
list.add(max);
}
return list;
}
}