leetcode 1161. 最大层内元素和 中等

给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。

返回总和 最大 的那一层的层号 x。如果有多层的总和一样大,返回其中 最小 的层号 x

示例 1:

复制代码
输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。

示例 2:

复制代码
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2

提示:

  • 树中的节点数在 [1, 10^4]范围内
  • -10^5 <= Node.val <= 10^5

分析:BFS 的模板题,对二叉树进行广度优先搜索,记录每一层的元素总和,保留元素之和最大的最小层号即可。

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:
    typedef struct node{
        TreeNode* p;
        int level;
    }node;
    int maxLevelSum(TreeNode* root) {
        int sum=0,index=1,maxn=root->val,ans=1;
        node temp;temp.p=root,temp.level=1;
        queue<node>que;que.push(temp);
        while(!que.empty())
        {
            node q=que.front();que.pop();
            if(q.p->left!=NULL)temp.p=q.p->left,temp.level=q.level+1,que.push(temp);
            if(q.p->right!=NULL)temp.p=q.p->right,temp.level=q.level+1,que.push(temp);

            if(q.level==index)sum+=q.p->val;
            else
            {
                if(sum>maxn)maxn=sum,ans=index;
                sum=q.p->val,index=q.level;
            }
        }
        if(sum>maxn)maxn=sum,ans=index;
        return ans;
    }
};
相关推荐
I_LPL16 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
灰色小旋风21 小时前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
阿里嘎多哈基米1 天前
速通Hot100-Day09——二叉树
算法·leetcode·二叉树·hot100
Frostnova丶1 天前
LeetCode 48 & 1886.矩阵旋转与判断
算法·leetcode·矩阵
多打代码1 天前
2026.3.22 回文子串
算法·leetcode·职场和发展
im_AMBER1 天前
Leetcode 144 位1的个数 | 只出现一次的数字
学习·算法·leetcode
小刘不想改BUG1 天前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
参.商.1 天前
【Day43】49. 字母异位词分组
leetcode·golang
参.商.1 天前
【Day45】647. 回文子串 5. 最长回文子串
leetcode·golang
Trouvaille ~1 天前
【优选算法篇】哈希表——空间换时间的极致艺术
c++·算法·leetcode·青少年编程·蓝桥杯·哈希算法·散列表