LeetCode 637 Average of Levels in Binary Tree

栏目: 数据库 · 发布时间: 7年前

内容简介:给予一颗二叉树,返回其每层节点的平均值.例 :采用广度优先遍历, 遍历每一行的数据, 相加并除以每一层的个数即可.

给予一颗二叉树,返回其每层节点的平均值.

例 :

给予树:
    3
   / \
  9  20
    /  \
   15   7
返回: [3, 14.5, 11]

解法

采用广度优先遍历, 遍历每一行的数据, 相加并除以每一层的个数即可.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                sum += node.val;

                if (node.left != null) {
                    queue.add(node.left);
                }

                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            result.add(sum / size);
        }
        return result;
    }
}
Runtime: 2 ms, faster than 99.14% of Java online submissions for Average of Levels in Binary Tree. Memory Usage: 39.2 MB, less than 99.96% of Java online submissions for Average of Levels in Binary Tree.

以上所述就是小编给大家介绍的《LeetCode 637 Average of Levels in Binary Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Concurrency on the JVM

Programming Concurrency on the JVM

Venkat Subramaniam / The Pragmatic Bookshelf / 2011-6-1 / USD 35.00

Concurrency on the Java platform has evolved, from the synchronization model of JDK to software transactional memory (STM) and actor-based concurrency. This book is the first to show you all these con......一起来看看 《Programming Concurrency on the JVM》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具