1. question: 在每个树行中找最大值(中等)
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
示例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
| 二叉树的节点个数的范围是 [0,104] -231 <= Node.val <= 231 - 1
|
2. answers
这道题比较简单,在层序遍历的基础上,即在遍历每一层的时候,保留最大值即可。代码如下所示:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public class Solution_0018 {
public static List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null) { return result; }
Queue<TreeNode> queue = new LinkedList<>(); int length, max = root.val;
queue.offer(root);
while(!queue.isEmpty()) {
length = queue.size(); max = queue.peek().val;
while(length > 0) {
root = queue.poll(); max = Math.max(max, root.val);
if(root.left != null) { queue.offer(root.left); }
if(root.right != null) { queue.offer(root.right); }
length --; }
result.add(max); }
return result; }
public static void main(String[] args) {
TreeNode tn1 = new TreeNode(5); TreeNode tn2 = new TreeNode(3); TreeNode tn3 = new TreeNode(3, tn1, tn2);
TreeNode tn4 = new TreeNode(9); TreeNode tn5 = new TreeNode(2, null, tn4);
TreeNode root = new TreeNode(1, tn3, tn5);
List<Integer> result = largestValues(root); for(Integer i: result){ System.out.println(i); }
} }
|
3. 备注
参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com),代码随想录 (programmercarl.com)。