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.
Analysis:
这题需要注意的是node中提到的整数范围,因为int能表示的最大整数是231−12^{31}-1231−1,因此这道题可能会出现多个接近232−12^{32}-1232−1的整数相加造成整数溢出的现象,简单的解决方法是将变量sum的类型设置为long。long能表示的最大整数是263−12^{63}-1263−1.
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> avgs = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(q.peek() != null) {
int size = q.size();
long sum = 0;
for(int i = 0; i < size; i++) {
TreeNode node = q.poll();
sum += node.val;
if(node.left != null) {
q.offer(node.left);
}
if(node.right != null) {
q.offer(node.right);
}
}
double avg = sum * 1.0 / size;
avgs.add(avg);
}
return avgs;
}
}
本文介绍了一种算法,用于计算给定非空二叉树各层节点的平均值,并以数组形式返回。通过使用队列进行层次遍历,算法能够有效地处理32位整数范围内的值,避免了整数溢出的问题。

被折叠的 条评论
为什么被折叠?



