题解 | #重量级的一层#

重量级的一层

https://www.nowcoder.com/practice/193372871b09426ab9ea805f0fd44d5c

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int maxLevelSum(TreeNode* root) 
    {
        // write code here
        if (root == NULL)
        {
            return 0;
        }
        queue<TreeNode*> que;
        que.push(root);
        int result = 0;
        int maxWeight = 0;
        int level = 0;
        while (!que.empty()) 
        {
            int n = que.size();
            int num = 0;
            level++;
            for (int i = 0;i < n;++i)
            {
                TreeNode* node = que.front();
                que.pop();
                num += node->val;
                if (node->left)
                {
                    que.push(node->left);
                }
                if (node->right)
                {
                    que.push(node->right);
                }
            }
            if (num >= maxWeight)
            {
                maxWeight = num;
                result = level;
            }
        }
        return result;
    }
};

全部评论

相关推荐

06-27 12:30
延安大学 C++
实习+外包,这两个公司底层融为一体了,如何评价呢?
一表renzha:之前面了一家外包的大模型,基本上都能答出来,那面试官感觉还没我懂,然后把我挂了,我都还没嫌弃他是外包,他把我挂了……
第一份工作能做外包吗?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:11
我最近都有点不想活了,天天早10晚11的,还问我爱不爱她目前的状态别说爱谁了,没扇谁就不错了。是不是大家都是一进节子,只有工作没有爱情了
AzureSkies:在字节的时候找的就是字节的,飞书太适合恋爱人士了,能看到是不是已读,是不是在会议中。简直冥婚好伴侣
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务