题目
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/
3 2
/ \ \
5 3 9
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/
2 3
输入: root = [1]
输出: [1]
输入: root = [1,null,2]
输出: [1,2]
解释:
1
2
输入: root = []
输出: []
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hPov7L
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:BFS
Java实现
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int sz = q.size();
int max = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
max = Math.max(max, cur.val);
}
res.add(max);
}
return res;
}
}