LeetCode - 637. Average of Levels in Binary Tree
Posted zyoung
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - 637. Average of Levels in Binary Tree相关的知识,希望对你有一定的参考价值。
链接
637. Average of Levels in Binary Tree
题意
给定非空二叉树,求出每一层数的平均值
思路
利用队列存储每一层的数,存完之后需要取出size,再循环求平均值。这样保证了循环的次数就是每一层的结点数。
代码
/**
* 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> result = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
if (root == null) return result;
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
double sum = 0.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);
}
result.add(sum / size);
}
return result;
}
}
以上是关于LeetCode - 637. Average of Levels in Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-637-Average of Levels in Binary Tree]
Leetcode 637. Average of Levels in Binary Tree
LeetCode: 637 Average of Levels in Binary Tree
LeetCode 637. 二叉树的层平均值(Average of Levels in Binary Tree)