100 % beat 18 ms


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<double> averageOfLevels(TreeNode* root) {
            vector<double>result;
            if(!root)
                return result;
            queue<TreeNode *> q;
            q.push(root);
            while(true)
            {
                int cnt = q.size();
                vector<int>v;
                if(!cnt)
                    break;
                int c = cnt;
                double x = 0;
                while(cnt--)
                {
                    TreeNode * temp = q.front();
                    q.pop();
                    x = x+temp->val;
                    if(temp->left)
                        q.push(temp->left);
                    if(temp->right)
                        q.push(temp->right);    
                }
                
                x = x/c;
                result.push_back(x);
                v.clear();
                x = 0;
                c =0;
            }
            return result;
            
        }
    };
    

Log in to reply
 

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