C++ DFS ,13ms


  • 0
    X

    Use recursion and parameter "level" to count the number of nodes and sum of node values in each level .

    class Solution {
    public:
        
        void averageCount(TreeNode *root,int level,vector<double> &averages,vector<int> &Lnodes)
        {
            if(!root) { return; }
            if(averages.size() == level ) { averages.push_back(root->val); Lnodes.push_back(1); }
            else { averages[level] += root->val; Lnodes[level]++; }
            
            averageCount(root->left,level+1,averages,Lnodes);
            averageCount(root->right,level+1,averages,Lnodes);
        }
        
        vector<double> averageOfLevels(TreeNode* root) {
            vector<double> averages;
            vector<int> Lnodes; //amount of nodes in levels
            
            averageCount(root,0,averages,Lnodes);
            for(int i=0;i<averages.size();++i) { averages[i] /= Lnodes[i]; }
            return averages;
        }
    };
    

Log in to reply
 

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