本文主要是介绍Leetcode—637.二叉树的层平均值【简单】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
这篇关于Leetcode—637.二叉树的层平均值【简单】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!