LeetCode.637.Average of Levels in Binary Tree 二叉树的层平均值

题目描述

637 Average of Levels in Binary Tree https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:The range of node's value is in the range of 32-bit signed integer.


解题过程

求二叉树每层的平均值,用层次遍历来做. 时间复杂度 O(n),空间复杂度 O(m),m是树中每一层节点个数的最大值

public List<Double> averageOfLevels(TreeNode root) {
    if (null == root) {
        return Collections.emptyList();
    }
    List<Double> res = new ArrayList<>();
    Deque<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        // 当前层的结点个数
        int size = queue.size();
        long sum = 0;
        for (int i = 0; i < size; i++) {
            TreeNode node =  queue.poll();
            sum += node.val;
            if (null != node.left) {
                queue.offer(node.left);
            }
            if (null != node.right) {
                queue.offer(node.right);
            }
        }
        res.add((double)sum / size);
    }
    return res;
}

GitHub代码

algorithms/leetcode/leetcode/_637_AverageOfLevelsInBinaryTree.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_637_AverageOfLevelsInBinaryTree.java