637. Average of Levels in Binary Tree 二叉树每层平均值

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
给定一非空二叉树,返回其每层的平均值所构成的数组。
Example 1:

Input:

    3
   / \
  9  20
    /  \
   15   7

Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node's value is in the range of 32-bit signed integer.

思路
【方法1】深度遍历
记录每层的结点总数和结点和。

/**
 * 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<int> count;
        vector<double> res;
        average(root,0,count,res);
        for(int i=0;i<res.size();i++){
            res[i]=res[i]/count[i];
        }
        return res;
    }
    void average(TreeNode *root, int i, vector<int> &count, vector<double> &sum){
        if(!root) return;
        if(i<sum.size()){
            sum[i]+=root->val;
            count[i]++;
        }
        else{
            sum.push_back(1.0*root->val);
            count.push_back(1);
        }
        average(root->left,i+1,count,sum);
        average(root->right,i+1,count,sum);
    }
};
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Integer> count=new ArrayList<>();
        List<Double> res=new ArrayList<>();
        average(root,0,count,res);
        for(int i=0;i<res.size();i++){
            res.set(i,res.get(i)/count.get(i));
        }
        return res;
    }
    public void average(TreeNode root, int i, List<Integer> count, List<Double> sum){
        if(root==null) return;
        if(i<sum.size()){
            sum.set(i,sum.get(i)+root.val);
            count.set(i,count.get(i)+1);
        }
        else{
            sum.add(1.0*root.val);
            count.add(1);
        }
        average(root.left,i+1,count,sum);
        average(root.right,i+1,count,sum);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,491评论 0 23
  • 大概是两年前吧,本着学英语的念头,一个师妹给我推荐了一部美剧就是这个大名顶顶的《Person of Interes...
    染尘阅读 2,532评论 0 0
  • 汽 是云的精灵 云 是雨雪的精灵 雨雪 是水的精灵 水 是万物的精灵 他分解自己 供给自然和人类 他的灵魂 在循环中永生
    童心_8c86阅读 2,967评论 12 31
  • 不喜欢占别人便宜,但也不喜欢老占别人便宜的那种人。有时候,会很生气,但气过后,又感觉有些后悔,有些不值得,何必要被...
    玻璃之森阅读 1,450评论 0 0
  • 往昔的我 虽孑然一身 但 至少 尚可 对影成双 而如今 ——没有了你 我才发现 我的影子 早已不见了 只因为 你是...
    七星二少阅读 1,261评论 0 0

友情链接更多精彩内容