2023每日刷题(二十五)
Leetcode—637.二叉树的层平均值
BFS实现代码
/*** 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().*/
#define MAXSIZE 10003double* averageOfLevels(struct TreeNode* root, int* returnSize) {double *ans = (double *)malloc(sizeof(double) * MAXSIZE);int front = 0, rear = 0;struct TreeNode** queue = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * MAXSIZE);queue[rear++] = root;int len = 0;int cnt = len;int pos = 0;while(front != rear) {len = rear - front;cnt = len;long long res = 0;while(len > 0) {len--;struct TreeNode* p = queue[front++];res += p->val;if(p->left != NULL) {queue[rear++] = p->left;}if(p->right != NULL) {queue[rear++] = p->right;}}double tmp = (double)res / cnt;ans[pos] = tmp;pos++;}*returnSize = pos;return ans;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!