题目链接
题目描述
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
- 二叉树的节点个数的范围是
[0,10^4]
- − 2 31 < = N o d e . v a l < = 2 31 − 1 -2^{31} <= Node.val <= 2^{31} - 1 −231<=Node.val<=231−1
解题思路
迭代法
层序遍历保存每一行的数值,每一行最终取最大值
AC代码
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) {
return ans;
}
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> itemList = new ArrayList<>();
int len = queue.size();
for (int i = 0; i < len; i++) {
TreeNode tmp = queue.poll();
itemList.add(tmp.val);
if (tmp.left != null) {
queue.offer(tmp.left);
}
if (tmp.right != null) {
queue.offer(tmp.right);
}
}
int min = Integer.MIN_VALUE;
for (Integer integer : itemList) {
min = Math.max(integer, min);
}
ans.add(min);
}
return ans;
}
}