[C++] Clean Code - BFS - 13ms


  • 0
    L
    class Solution {
    public:
        vector<double> averageOfLevels(TreeNode* root) {
            vector<double> result;
            if (root == nullptr) return result;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                queue<TreeNode*> new_q;
                double level = 0;
                int num = 0;
                while (!q.empty()) {
                    TreeNode* temp = q.front();
                    q.pop();
                    level += temp->val;
                    ++num;
                    if (temp->left != nullptr) new_q.push(temp->left);
                    if (temp->right != nullptr) new_q.push(temp->right);
                }
                result.emplace_back(level / num);
                q = new_q;  
            }
            return result;
        }
    };
    

Log in to reply
 

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