xinyu04

导航

[Oracle] LeetCode 1161 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.

Solution

直接用 \(queue\)\(BFS\), 遍历每一层更新答案

点击查看代码
/**
 * 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 {
private:
    queue<TreeNode*> q;
    int ans = INT_MIN;
    int lev = 0;
public:
    int maxLevelSum(TreeNode* root) {
        q.push(root);
        int real_lev=0;
        while(!q.empty()){
            int t = q.size();
            int sum=0;
            real_lev++;
            while(t--){
                auto f = q.front(); q.pop();
                sum+= f->val;
                if(f->left)q.push(f->left);
                if(f->right)q.push(f->right);
            }
            //cout<<sum<<endl;
            if(sum>ans){ans=sum;lev=real_lev;}
            //cout<<lev<<endl;
        }
        return lev;
    }
};








posted on 2022-08-25 15:49  Blackzxy  阅读(14)  评论(0编辑  收藏  举报