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;
    }
};
相关推荐
玖笙&2 分钟前
✨WPF编程进阶【7.2】:动画类型(附源码)
c++·c#·wpf·visual studio
汗流浃背了吧,老弟!8 分钟前
中文分词全切分算法
算法·中文分词·easyui
~~李木子~~14 分钟前
贪心算法实验1
算法·ios·贪心算法
上去我就QWER38 分钟前
C++标准库中的排序算法
c++·排序算法
·云扬·39 分钟前
【LeetCode Hot 100】 136. 只出现一次的数字
算法·leetcode·职场和发展
Xiaochen_1241 分钟前
有边数限制的最短路:Bellman-Ford 算法
c语言·数据结构·c++·程序人生·算法·学习方法·最简单的算法理解
AA陈超1 小时前
ASC学习笔记0019:返回给定游戏属性的当前值,如果未找到该属性则返回零。
c++·笔记·学习·游戏·ue5·虚幻引擎
阿沁QWQ1 小时前
HTTP cookie 与 session
c++·浏览器·edge浏览器·cookie·session
熬了夜的程序员2 小时前
【LeetCode】114. 二叉树展开为链表
leetcode·链表·深度优先
铅笔小新z3 小时前
C++入门指南:开启你的编程之旅
开发语言·c++