描述
分析
二叉树的层序遍历。
层序遍历需要用到队列。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Double> res = new ArrayList<>();
public List<Double> averageOfLevels(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
bfs(queue);
return res;
}
public void bfs(Queue<TreeNode> queue) {
int len = queue.size(); // 获取这一层的节点数
if(len == 0) return;
long sum = 0; // 注意,放置int类型溢出,使用long型
for (int i = 0; i < len; i++) {
TreeNode node = queue.poll(); // 取出
sum += node.val;
if (node.left != null) {
queue.offer(node.left); // 左节点放入队列
}
if (node.right != null) {
queue.offer(node.right); // 右节点放入队列
}
}
res.add((double) sum / (double) len);
bfs(queue);
}
}