c++ bfs


  • 0
    D

    Pretty straight forward solution.
    You might need to be aware that the sum could be more than INT_MAX. So the "long" is required.

      vector<double> averageOfLevels(TreeNode* root) {
            vector<double> ret;
            
            queue<TreeNode*> q;
            q.push(root);
            
            while(!q.empty()){
                long sum = 0;
                int len = q.size();
                for(int i = 0; i < len; ++i){
                    TreeNode *n = q.front(); q.pop();
                    sum += n->val;
                    if (n->left) q.push(n->left);
                    if (n->right) q.push(n->right);
                }
                ret.push_back((double)sum/len);
            }
            
            return ret;
        }
    

Log in to reply
 

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