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 averageOfLevels(TreeNode* root) {
        vector count;
        vector res;
        average(root,0,count,res);
        for(int i=0;i &count, vector &sum){
        if(!root) return;
        if(ival;
            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 averageOfLevels(TreeNode root) {
        List count=new ArrayList<>();
        List res=new ArrayList<>();
        average(root,0,count,res);
        for(int i=0;i count, List sum){
        if(root==null) return;
        if(i

你可能感兴趣的:(637. Average of Levels in Binary Tree 二叉树每层平均值)