Simple C++ BF traversal


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

Log in to reply
 

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