C++ simple and clear BFS solution


  • 3
    M
        vector<double> averageOfLevels(TreeNode* root) {
            vector<double> res;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()) {
                long temp=0;
                int s=q.size();
                for(int i=0;i<s;i++) {
                    TreeNode* t=q.front();
                    q.pop();
                    if(t->left) q.push(t->left);
                    if(t->right) q.push(t->right);
                    temp+=t->val;
                }
                res.push_back((double)temp/s);
            }
            return res;
        }

Log in to reply
 

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