给定一棵二叉树的根节点 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路及方法
BFS,每一层遍历寻找最大值。
/**
* 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> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> trees = new LinkedList<>();
// 根节点入队
trees.offer(root);
while (!trees.isEmpty()) {
int size = trees.size();
int rowMax = Integer.MIN_VALUE;
// 遍历每一行
for (int i = 0; i < size; i++) {
TreeNode cur = trees.poll();
rowMax = Math.max(cur.val, rowMax);
// 子节点入队
if (cur.left != null) trees.offer(cur.left);
if (cur.right != null) trees.offer(cur.right);
}
res.add(rowMax);
}
return res;
}
}
结果如下:
网友评论