Leetcode637. 二叉树的层平均值(遍历,深度,每层个数)

https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:

输入:
    3
   / \
  9  20
    /  \
   15   7
输出: [3, 14.5, 11]
解释:0层的平均值是 3,1层是 14.5,2层是 11. 因此返回 [3, 14.5, 11].
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

/* 思路:
先遍历一下二叉树,求出深度
在遍历一下二叉树,求出平均值
*/
int depth_tree(struct TreeNode* root){
    if(!root) return 0;
    int depthl = depth_tree(root->left);
    int depthr = depth_tree(root->right);
    return 1 + (depthl > depthr ? depthl : depthr); 
}

void average_treeval(struct TreeNode* root, double *ret, int depth, int *count){
    if(!root) return;
    ret[depth] += root->val;
    count[depth]++;
    
    depth++;
    average_treeval(root->left, ret, depth, count);
    average_treeval(root->right, ret, depth, count);
}

double* averageOfLevels(struct TreeNode* root, int* returnSize){
    int depth = 0;
    depth = depth_tree(root);
    
    double *ret = (double *)calloc(depth, sizeof(double));  // ret中先存和
    int *count = (int *)calloc(depth, sizeof(int));  //count中存每层的个数
    average_treeval(root, ret, 0, count);
    
    int d = 0;
    for(; d < depth; d++){
        ret[d] = ret[d] / count[d];
    }
    
    *returnSize = depth;
    return ret;
}

你可能感兴趣的:(LeetCode题解)