[C++] Clean Code - DFS


  • 0
    class Solution {
    public:
        vector<double> averageOfLevels(TreeNode* root) {
            map<int, pair<long, int>> info;
            getLevelInfo(root, 0, info);
    
            vector<double> avgs(info.size());
            for (auto it = info.begin(); it != info.end(); it++) {
                long total = it->second.first;
                int nodes = it->second.second;
                avgs[it->first] = ((double)total) / nodes;
            }
            return avgs;
        }
    
    private:
        void getLevelInfo(TreeNode* node, int l, map<int, pair<long, int>>& info) {
            if (!node) return;
            info[l].first += node->val;
            info[l].second++;
            getLevelInfo(node->left, l + 1, info);
            getLevelInfo(node->right, l + 1, info);
        }
    };
    

Log in to reply
 

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