Average of Levels in Binary Tree


  • 0
    S

    /**

    • 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:
      int calc(TreeNode
      root)
      {
      if(root == NULL)
      return 0;

       int lheight = calc(root->left);
       int rheight = calc(root->right);
       
       return lheight>=rheight?1+lheight:1+rheight;
      

      }
      void levelOrder(vector<vector<int>> &ans, TreeNode *node, int level) {
      if (!node) return;
      if (level >= ans.size())
      ans.push_back({});
      ans[level].push_back(node->val);
      levelOrder(ans,node->left,level+1);
      levelOrder(ans,node->right,level+1);

    }

    vector<double> averageOfLevels(TreeNode* root) {
        vector<vector<int>> ans;
        levelOrder(ans,root,0);
        int height = calc(root);
        vector<double> result;
        double average;
        for(int i = 0; i<height;i++)
        {
            
            average = accumulate( ans[i].begin(), ans[i].end(),0.0)/ans[i].size();
            result.push_back(average);
        }
        
        return result;
    }
    

    };


Log in to reply
 

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