内容简介:给予一颗二叉树,返回其每层节点的平均值.例 :采用广度优先遍历, 遍历每一行的数据, 相加并除以每一层的个数即可.
给予一颗二叉树,返回其每层节点的平均值.
例 :
给予树: 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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- LeetCode 637 Average of Levels in Binary Tree
- Leetcode PHP题解--D56 637. Average of Levels in Binary Tree
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。