LeetCode1161. 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

二、题解

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxLevelSum(TreeNode* root) {
        int res = 1;
        int maxSum = INT_MIN;
        queue<TreeNode*> q;
        q.push(root);
        int level = 0;
        while(!q.empty()){
            int size = q.size();
            int sum = 0;
            level++;
            while(size--){
                TreeNode* t = q.front();
                q.pop();
                sum += t->val;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            if(sum > maxSum){
                maxSum = sum;
                res = level;
            }
        }
        return res;
    }
};
相关推荐
鹿角片ljp7 分钟前
LeetCode 22:括号生成|回溯dfs、剪枝与 char[] 覆盖代替撤销
算法·深度优先
sylviiiiiia23 分钟前
leetcode hot100
python·算法·leetcode
纪伊路上盛名在36 分钟前
Kabsch算法的Julia实现
开发语言·算法·julia·序列分析·蛋白质·rmsd
水饺编程1 小时前
编程数学:三角函数基础01,直角三角函数
c语言·c++·windows·visual studio
裕晟资质规划1 小时前
军工保密资质二级申报的四个可量化硬条件:条文位置、数值口径与西安配套企业实务要点
java·服务器·网络·数据库·算法
LuminousCPP1 小时前
数据结构-排序(一):基础排序算法横向对比|冒泡、插入、希尔、堆与双向选择,详解二分 / Knuth 增量
c语言·数据结构·笔记·算法·排序算法
初願致夕霞1 小时前
C/C++传统程序内存分布(代码实测)
java·c语言·c++
牛油果子哥q1 小时前
C++对接LLM完整工程:异步HTTP请求、JSON解析、超时容错、重连兜底
c++·http·json
Nil2081 小时前
leetcode 46全排列
算法·leetcode·职场和发展
辰烨chenye1 小时前
LeetCode Hot 100 题解 · 动态规划篇
算法·leetcode·动态规划