[LeetCode] 1161. Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

Example 1:

Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation: 
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Example 2:

Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105

最大层内元素和。

给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。

请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题不难,属于树的BFS遍历。注意记录一个层数 level,如果当前层的节点值的和是最大的,不但要记录这个最大的和是多少,同时要记录一下这是第几层。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public int maxLevelSum(TreeNode root) {
18         int res = Integer.MIN_VALUE;
19         int level = 1;
20         int maxLevel = 1;
21         Queue<TreeNode> queue = new LinkedList<>();
22         queue.offer(root);
23         while (!queue.isEmpty()) {
24             int size = queue.size();
25             int sum = 0;
26             for (int i = 0; i < size; i++) {
27                 TreeNode cur = queue.poll();
28                 sum += cur.val;
29                 if (cur.left != null) {
30                     queue.offer(cur.left);
31                 }
32                 if (cur.right != null) {
33                     queue.offer(cur.right);
34                 }
35             }
36             if (sum > res) {
37                 maxLevel = level;
38                 res = sum;
39             }
40             level++;
41         }
42         return maxLevel;
43     }
44 }

 

LeetCode 题目总结

posted @ 2022-07-31 06:19  CNoodle  阅读(48)  评论(0编辑  收藏  举报