/**
* 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> ans = new LinkedList<>();
Queue<TreeNode> queue = new LinkedList<>();
// base case
if (root == null) return ans;
queue.offer(root);
// 层序遍历
while (!queue.isEmpty()) {
double sum = 0;
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
sum += node.val;
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
ans.add(sum/size);
}
return ans;
}
}
leecode-637-二叉树的层平均值
最新推荐文章于 2021-03-21 14:15:07 发布