Leetcode637. 두 갈래 나무의 층 평균치(반복, 깊이, 층당 개수)

9404 단어 LeetCode 문제
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;
}

좋은 웹페이지 즐겨찾기