当前位置:网站首页>Ringtone 1161. Maximum In-Layer Elements and
Ringtone 1161. Maximum In-Layer Elements and
2022-08-02 02:08:00 【cold-blooded fisherman】
题目
给你一个二叉树的根节点 root.设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推.
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个.
示例

输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大.
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree
著作权归领扣网络所有.商业转载请联系官方授权,非商业转载请注明出处.
方法1:BFS
Java实现
class Solution {
public int maxLevelSum(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int res = -1, step = 1;
int sum, max = Integer.MIN_VALUE;
while (!q.isEmpty()) {
sum = 0;
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
sum += cur.val;
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
if (sum > max) {
max = sum;
res = step;
}
step++;
}
return res;
}
}

边栏推荐
猜你喜欢

oracle query scan full table and walk index

【Brush the title】Family robbery

LeetCode刷题日记:LCP 03.机器人大冒险

【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例

Constructor of typescript35-class

Typescript31 - any type

hash table

AOF重写

Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion

3. Bean scope and life cycle
随机推荐
Data transfer at the data link layer
手写一个博客平台~第一天
Fly propeller power space future PIE - Engine Engine build earth science
Handwriting a blogging platform ~ the first day
拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货
『网易实习』周记(二)
编码经验之谈
【ORB_SLAM2】SetPose、UpdatePoseMatrices
Constructor instance method inheritance of typescript37-class (extends)
Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
成都openGauss用户组招募啦!
Basic use of typescript34-class
力扣 1161. 最大层内元素和
openGauss切换后state状态显示不对
Simple example of libcurl accessing url saved as file
[LeetCode Daily Question]——654. The largest binary tree
Redis for distributed applications in Golang
MySQL optimization strategy
【LeetCode每日一题】——654.最大二叉树
Fundamentals of Cryptography: X.690 and Corresponding BER CER DER Encodings