ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-07-31 06:31:07  阅读:185  来源: 互联网

标签:Binary TreeNode 1161 val level int sum Level null


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 题目总结

标签:Binary,TreeNode,1161,val,level,int,sum,Level,null
来源: https://www.cnblogs.com/cnoodle/p/16536368.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有