637. 二叉树的层平均值
637. Average of Levels in Binary Tree
LeetCode637. Average of Levels in Binary Tree
题目描述
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ 9 20
/ 15 7
输出: [3, 14.5, 11]
解释:
第 0 层的平均值是 3,第 1 层是 14.5,第 2 层是 11.因此返回 [3, 14.5, 11].
注意:
- 节点值的范围在32位有符号整数范围内。
Java 实现
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
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 LinkedList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
return result;
}
queue.offer(root);
while (!queue.isEmpty()) {
double avg = 0.0;
int size = queue.size();
for (int i = 0; i < size; i++) {
if (queue.peek().left != null) {
queue.offer(queue.peek().left);
}
if (queue.peek().right != null) {
queue.offer(queue.peek().right);
}
avg += queue.poll().val;
}
result.add(avg / size);
}
return result;
}
}
相似题目
参考资料
- https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
- https://leetcode.com/problems/average-of-levels-in-binary-tree/
原文地址:https://www.cnblogs.com/hglibin/p/10849802.html
时间: 2024-11-10 12:07:09