101 字
1 分钟
LeetCode 面试经典150题 [75/150 二叉树的层平均值]
题目描述
给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。
示例 1:
输入:root = [3,9,20,null,null,15,7]输出:[3.00000,14.50000,11.00000]解释:第 0 层的平均值为 3,第 1 层的平均值为 14.5,第 2 层的平均值为 11 。因此返回 [3, 14.5, 11] 。示例 2:
输入:root = [3,9,20,15,7]输出:[3.00000,14.50000,11.00000]个人C++解答
套用上一道题的层次遍历的模板,稍作修改,主要是double类型可能会出错;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), * right(right) {} * }; */class Solution {public: vector<double> averageOfLevels(TreeNode* root) { vector<TreeNode*> q; vector<double> ans; q.push_back(root); while (!q.empty()) { vector<TreeNode*> vec; double count = 0, sum = 0; for (int i = 0; i < q.size(); i++) { count++; sum += (q[i]->val); TreeNode* node = q[i]; if (node->left) vec.push_back(node->left); if (node->right) vec.push_back(node->right); } ans.push_back(sum / count); q = move(vec); } return ans; }}; 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
LeetCode 面试经典150题 [75/150 二叉树的层平均值]
https://ericonline.cn/posts/leetcode-面试经典150题-75-150-二叉树的层平均值/ 部分信息可能已经过时
相关文章 智能推荐
1
LeetCode 面试经典150题 [76/150 二叉树的层序遍历]
LeetCode 题解 2024-07-31
2
LeetCode 面试经典150题 [74/150 二叉树的右视图]
LeetCode 题解 2024-07-31
3
LeetCode 面试经典150题 [64/150 二叉树的最大深度]
LeetCode 题解 2024-07-11
4
LeetCode 面试经典150题 [77/150 二叉树的锯齿形层序遍历]
LeetCode 题解 2024-07-31
5
LeetCode 面试经典150题 [67/150 对称二叉树]
LeetCode 题解 2024-07-16