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;
    }
};
相关推荐
_dindong29 分钟前
牛客101:二叉树
数据结构·c++·笔记·学习·算法
数字化脑洞实验室1 小时前
如何理解不同行业AI决策系统的功能差异?
大数据·人工智能·算法
人邮异步社区2 小时前
推荐几本学习计算机语言的书
java·c语言·c++·python·学习·golang
潼心1412o4 小时前
数据结构(长期更新)第5讲:单链表算法题
数据结构
ha20428941944 小时前
Linux操作系统学习之---线程池
linux·c++·学习
小白菜又菜5 小时前
Leetcode 3370. Smallest Number With All Set Bits
算法·leetcode·职场和发展
A-code5 小时前
C/C++ 中 void* 深度解析:从概念到实战
c语言·开发语言·c++·经验分享·嵌入式
星谷罗殇5 小时前
(七)TRPO 算法 & PPO 算法
算法·机器学习
国服第二切图仔7 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust
电鱼智能的电小鱼7 小时前
基于电鱼 ARM 工控机的井下AI故障诊断方案——让煤矿远程监控更智能、更精准
网络·arm开发·人工智能·算法·边缘计算