【精】领扣LintCode算法问题答案:1115. 二叉树每层的平均数
发布日期:2021-06-30 17:09:53 浏览次数:2 分类:技术文章

本文共 1736 字,大约阅读时间需要 5 分钟。

1115. 二叉树每层的平均数

描述

给定非空二叉树,以数组的形式返回每一层上的节点的平均值。

样例 1:

输入:    3   / \  9  20     /  \   15   7输出: 	[3, 14.5, 11]解释:	第0层的节点的平均值是3,第一层的平均值是14.5, 第二层的平均值11,因此需要返回[3, 14.5, 11]


文章目录


分析

按层序遍历,每次统计这一层的节点数和节点值之和。

题解

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {
/** * @param root: the binary tree of the root * @return: return a list of double */ public List
averageOfLevels(TreeNode root) {
// write your code here List
ret = new ArrayList<>(); if (root == null) {
return ret; } // 第一层 ret.add(Double.valueOf(root.val)); // 将第二层入队 Queue
q = new LinkedList<>(); if (root.left != null) {
q.offer(root.left); } if (root.right != null) {
q.offer(root.right); } while (!q.isEmpty()) {
// 每次循环一层,记录节点数量,和节点值之和 int size = q.size(); double totalValue = 0; for (int i = 0; i < size; ++i) {
TreeNode node = q.poll(); totalValue += node.val; if (node.left != null) {
q.offer(node.left); } if (node.right != null) {
q.offer(node.right); } } // 一层的平均值 ret.add(totalValue / size); } return ret; }}

最后说两句

非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

作者水平有限,如果文章内容有不准确的地方,请指正。

希望小伙伴们都能每天进步一点点。

声明

本文由博客原创,转载请注明来源,谢谢~

转载地址:https://le-yi.blog.csdn.net/article/details/108841688 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1119. 三个数的最大乘积
下一篇:【精】LintCode领扣算法问题答案:1112. 寻找数据错误

发表评论

最新留言

不错!
[***.144.177.141]2024年05月02日 03时00分10秒