题目:
Given a non-empty binary tree, return the average value of the nodes
on each level in the form of an array.
Example 1:Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Note: The range of node's value is in the range of 32-bit signed integer.
解释:
求二叉树每层的均值,也是用层序遍历的经典解法求解。
python写法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if not root:
return []
queue=[root]
result=[]
while queue:
layer_len=len(queue)
temp=[]
for i in range(layer_len):
cur_node=queue[0]
temp.append(cur_node.val)
if cur_node.left!=None:
queue.append(cur_node.left)
if cur_node.right!=None:
queue.append(cur_node.right)
queue.pop(0)
result.append(sum(temp)/layer_len)
return result
c++写法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <vector>
#include <queue>
#include <numeric>
using namespace std;
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> result;
if (!root)
return result;
queue<TreeNode*> _queue;
_queue.push(root);
while (_queue.size()!=0)
{
int layer_len=_queue.size();
vector<int> temp;
for(int i=0;i<layer_len;i++)
{
TreeNode* cur_node=_queue.front();
if (cur_node->left)
_queue.push(cur_node->left);
if (cur_node->right)
_queue.push(cur_node->right);
temp.push_back(cur_node->val);
_queue.pop();
}
long double _sum=accumulate(temp.begin(),temp.end(),0.0);
result.push_back(_sum/layer_len);
}
return result;
}
};
总结:
学会使用<numeric>
中的accumulate()
累加求和函数,accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。
调用accumulate函数必须满足的条件包括:容器内的元素类型必须与第三个实参的类型匹配,或者可转换为第三个实参的类型。所以要防止初始值的类型不对而造成报错或者精度的缺失。