my c++ version with queue which beats 96.45 % of cpp submissions


  • 0
    class Solution {
    public:
        vector<double> averageOfLevels(TreeNode* root) {
            vector<double> res;
            if (!root) return res;
            queue<TreeNode*> que;
            que.push(root);
            
            while(!que.empty())
            {
                long sum = 0;
                int size = que.size();
                for (int i = 0;i < size;i++)
                {
                    TreeNode* cur = que.front();
                    sum += cur->val;
                    que.pop();
                    if (cur->left) que.push(cur->left);
                    if (cur->right) que.push(cur->right);
                }
                res.push_back(sum / static_cast<double>(size));
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.