LeetCode 637 Average of Levels in Binary Tree

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

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

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

例 :

给予树:
    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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Software Engineering for Internet Applications

Software Engineering for Internet Applications

Eve Andersson、Philip Greenspun、Andrew Grumet / The MIT Press / 2006-03-06 / USD 35.00

After completing this self-contained course on server-based Internet applications software, students who start with only the knowledge of how to write and debug a computer program will have learned ho......一起来看看 《Software Engineering for Internet Applications》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试