面试必考精华版Leetcode最大层内元素和

题目:

面试必考精华版Leetcode最大层内元素和_第1张图片


代码(首刷看解析):

class Solution {
public:
    int maxLevelSum(TreeNode* root) {
        int ans =1,maxSum=root->val;
        vector q = {root};
        for(int level = 1;!q.empty();++level){
            vector nq;
            int sum=0;
            for(auto node:q){
                sum+=node->val;
                if(node->left) nq.push_back(node->left);
                if(node->right) nq.push_back(node->right);
            }
            if(sum>maxSum){
                maxSum=sum;
                ans=level;
            }
            q=move(nq);
        }
        return ans;
    }
};

你可能感兴趣的:(#,leetcode,---medium,前端,算法,javascript)