在每个树行中找最大值

算法-在每个树行中找最大值

背景

  • 算法–在每个树行中找最大值

  • 博主以代码随想录算法公开课进行学习

题目

  • 给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

    示例1:

    1
    2
    输入: root = [1,3,2,5,3,null,9]
    输出: [1,3,9]

    示例2:

    1
    2
    输入: root = [1,2,3]
    输出: [1,3]

思路

  • 与层序遍历一致

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 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) {
if(root == null){
return Collections.emptyList();
}
List<Integer> result = new ArrayList();
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
// 初始化当前层的最大值为整数最小值(确保任何节点值都能覆盖它)
int max = Integer.MIN_VALUE;
for(int i = queue.size();i > 0;i--){
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);
}
}
result.add(max);
}
return result;
}
}