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;
    }
};
相关推荐
星恒随风1 分钟前
C++ 多态底层原理:静态绑定、动态绑定、虚函数表与工程实践
开发语言·c++·笔记·学习
白色冰激凌15 分钟前
[SECS/GEM研究] (四)HSMS 用TCP取代串口
网络·c++·网络协议·secs/gem
来一碗刘肉面27 分钟前
字符串模式匹配(朴素模式匹配算法与KMP算法)
数据结构·算法
go不是csgo38 分钟前
从模板到五道 LeetCode:完全背包的 Golang 教学笔记
笔记·leetcode·golang
dyxal44 分钟前
eˣ 的泰勒展开式:从“化繁为简”到“万物统一”的微积分之美
算法
BetterFlow_CFD1 小时前
COMSOL声学仿真基础知识(二)
开发语言·算法·matlab
ShineWinsu1 小时前
对于Linux:http的解析
linux·网络·c++·网络协议·http·请求·响应
choumin10 小时前
创建型模式——工厂方法模式
c++·设计模式·工厂方法模式·创建型模式
云小逸11 小时前
【SVN 详细使用指南:从入门到团队协作】
c++·svn
徐小夕12 小时前
花了一周,3亿tokens,我开源了一款 Word 文档智能审查平台,文稿自动质检+可视化分析,告别低效人工审核
前端·算法·github