当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.637.Average of Levels in Binary Tree 二叉树的层平均值

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


上一篇 LeetCode.653.Two Sum IV - Input is a BST 两数之和4-输入是BST

下一篇 LeetCode.617.Merge Two Binary Trees 合并二叉树

阅读
评论
259
阅读预计1分钟
创建日期 2020-01-31
修改日期 2020-01-31
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论