zoukankan      html  css  js  c++  java
  • Leetcode 637. Average of Levels in Binary Tree

    题目链接

    https://leetcode.com/problems/average-of-levels-in-binary-tree/description/

    题目描述

    Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

    Example 1:

    Input:
        3
       / 
      9  20
        /  
       15   7
    Output: [3, 14.5, 11]
    Explanation:
    The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
    
    

    Note:

    1. The range of node's value is in the range of 32-bit signed integer.

    题解

    依次遍历每一层,统计结果并求出平均值。

    代码

    /**
     * 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> list = new ArrayList<>();
            if (root == null) { return list; }
            LinkedList<TreeNode> s = new LinkedList<>();
            s.offer(root);
            while (!s.isEmpty()) {
                int size = s.size();
                double sum = 0;
                for (int i = 0; i < size; i++) {
                    TreeNode node = s.poll();
                    if (node.left != null) { 
                        s.offer(node.left);
                    }
                    if (node.right != null) {
                        s.offer(node.right);
                    }
                    sum += (double)node.val;
                }
                list.add(sum / size);
            }
            return list;
        }
    }
    
  • 相关阅读:
    寻找两个有序数组的中位数
    JAVA设计模式(组合模式)
    excel 操作
    研究生英语-春
    cvs
    Spring课程安排
    Spring的事务管理
    在WEB项目中集成Spring
    计算机网络参考模型
    揭开5G神秘面纱
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9596627.html
Copyright © 2011-2022 走看看