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;
    }
};
相关推荐
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll5 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐5 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶5 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER5 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了5 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333336 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录6 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1236 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode