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;
    }
};
相关推荐
肖田变强不变秃43 分钟前
C++实现有限元计算 矩阵装配Assembly类
开发语言·c++·矩阵·有限元·ansys
c++初学者ABC1 小时前
学生管理系统C++版(简单版)详解
c++·结构体·学生管理系统
kucupung1 小时前
【C++基础】多线程并发场景下的同步方法
开发语言·c++
L73S372 小时前
C++入门(1)
c++·程序人生·考研·蓝桥杯·学习方法
Bunury2 小时前
组件封装-List
javascript·数据结构·list
Joeysoda2 小时前
Java数据结构 (从0构建链表(LinkedList))
java·linux·开发语言·数据结构·windows·链表·1024程序员节
迂幵myself2 小时前
14-6-1C++的list
开发语言·c++·list
天乐敲代码2 小时前
JAVASE入门九脚-集合框架ArrayList,LinkedList,HashSet,TreeSet,迭代
java·开发语言·算法
比特在路上2 小时前
ListOJ14:环形链表II(寻找环的入口点)
数据结构·链表
十年一梦实验室2 小时前
【Eigen教程】矩阵、数组和向量类(二)
线性代数·算法·矩阵