【leetcode】637. 二叉树的层平均值

 

double* averageOfLevels(struct TreeNode* root, int* returnSize){
    struct TreeNode* tn[1000];
    double* arr=(double*)calloc(1000,sizeof(double));
    int left=0, right=0, i, pst=0, sum=0;
    tn[right++]=root;
    while(left<=right){
        sum=0;
        int len=right-left;
        for(i=left; i<left+len; i++){
            if(tn[i]->left)
                tn[right++]=tn[i]->left;
            else if(tn[i]->right)
                tn[right++]=tn[i]->right;
            sum += tn[i]->val;
        }
        left+=len;
        arr[pst++]=sum/len;
    }
    *returnSize=pst;
    return arr;
}

 

posted @ 2020-12-01 15:24  温暖了寂寞  阅读(50)  评论(0编辑  收藏  举报