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);
    }
}
    原文作者:这就是一个随意的名字
    原文地址: https://www.jianshu.com/p/07e5c642a3f2
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞