• [637] 二叉树的层平均值


    /*
     * @lc app=leetcode.cn id=637 lang=java
     *
     * [637] 二叉树的层平均值
     *
     * https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/
     *
     * algorithms
     * Easy (56.65%)
     * Total Accepted:    3.9K
     * Total Submissions: 6.9K
     * Testcase Example:  '[3,9,20,15,7]'
     *
     * 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
     * 
     * 示例 1:
     * 
     * 输入:
     * ⁠   3
     * ⁠  / 
     * ⁠ 9  20
     * ⁠   /  
     * ⁠  15   7
     * 输出: [3, 14.5, 11]
     * 解释:
     * 第0层的平均值是 3,  第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
     * 
     * 
     * 注意:
     * 
     * 
     * 节点值的范围在32位有符号整数范围内。
     * 
     * 
     */
    /**
     * 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> resultList = new ArrayList<Double>();
            if (root == null) {
                return null;
            }
            LinkedList<TreeNode> list = new LinkedList<TreeNode>();  
            list.add(root);
            
            while (!list.isEmpty()) {
                double sum = 0.0;
                int size = list.size();
                for (int i=0;i<size;i++) {
                   TreeNode currentNode = list.poll();
                    sum+=currentNode.val;
                    if (currentNode.left != null) {
                        list.add(currentNode.left);
                    }
                    if (currentNode.right != null) {
                        list.add(currentNode.right);
                    }
                }
                resultList.add(sum/size);
            }
            return resultList;
        }
    }
    

      

  • 相关阅读:
    Springboot演示小Demo
    快速构建一个 Springboot
    javase练习题--每天写写
    javase练习题
    WebDriver API——延时操作及元素等待
    WebDriver API——javascript的相关操作
    Jenkins安装部署及tomcat的入门介绍
    WebDriver API——鼠标及键盘操作Actions
    sql查询练习
    睡前反省,絮叨絮叨
  • 原文地址:https://www.cnblogs.com/airycode/p/10475326.html
Copyright © 2020-2023  润新知