0637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree #

题目 #

给定一个非空二叉树的根节点 root,以数组的形式返回每一层节点的平均值。

与实际答案相差 10^-5 以内的答案可以被接受。

思路 #

代码 #

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 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> ans = new LinkedList<>();
        if (root == null) return ans;
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.size() != 0) {
            int layerSize = queue.size();
            double sum = 0;
            for (int i = 0; i < layerSize; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                sum += node.val;
            }
            ans.add(sum / layerSize);
        }
        
        return ans;
    }
}