A more clear c++ solution


  • 0
    C
    class Solution {
     public:
      vector<double> averageOfLevels(TreeNode *root)
      {
        vector<double> ret;
        if (root == NULL)
          return ret;
    
        vector<TreeNode *> v;
        v.push_back(root);
        int curr = 0, last = 1;
        double sum, num;
        while (curr < v.size()) {
          last = v.size();
          sum = num = 0;
          while (curr < last) {
            num++;
            sum += v[curr]->val;
            if (v[curr]->left)
              v.push_back(v[curr]->left);
            if (v[curr]->right)
              v.push_back(v[curr]->right);
            curr++;
          }
          ret.push_back(sum/num);
        }
    
        return ret;
      }
    };
    

Log in to reply
 

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