当前位置: 代码迷 >> 综合 >> 领扣LintCode算法问题答案-1115. 二叉树每层的平均数
  详细解决方案

领扣LintCode算法问题答案-1115. 二叉树每层的平均数

热度:92   发布时间:2024-02-23 19:20:48.0

领扣LintCode算法问题答案-1115. 二叉树每层的平均数

目录

  • 1115. 二叉树每层的平均数
    • 描述
    • 样例 1:
  • 题解
  • 鸣谢

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<Double> averageOfLevels(TreeNode root) {
    // write your code hereList<Double> ret = new ArrayList<>();if (root == null) {
    return ret;}ret.add(Double.valueOf(root.val));Queue<TreeNode> 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;}
}

原题链接点这里

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。