637. 二叉树的层平均值

637. 二叉树的层平均值

原题

/**
 * 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 {
    public List<Double> averageOfLevels(TreeNode root) {
        if(root==null){
            return null;
        }
        //返回结果
        List<Double> list = new ArrayList<>();
        //统计队列中每层的大小
        int size = 0;
        //计算每层的和
        double sum = 0;
        //队列--实现层序遍历
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            //获取当前队列有多少个元素
            size = q.size();
            sum = 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);
            }
            //添加结果集
            list.add(sum/size);
        }
        return list;
    }
}

你可能感兴趣的:(LeetCode刷题,广度优先)