zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 637 二叉树的层平均值(遍历树)

    637. 二叉树的层平均值

    给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

    示例 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> res = new ArrayList<>();
            if (root == null) return res;
            Queue<TreeNode> list = new LinkedList<>();
            list.add(root);
            while (list.size() != 0){
                int len = list.size();
                double sum = 0;
                for (int i = 0; i < len; i++){
                    TreeNode node = list.poll();
                    sum += node.val;
                    if (node.left != null) list.add(node.left);
                    if (node.right != null) list.add(node.right);
                }
                res.add(sum/len);
            }
            return res;
        }
    }
    
  • 相关阅读:
    Swift Optional
    cocoapods 配置
    winform窗体全屏
    SQLiteDatabase的使用
    探索Gallery和ImageSwitcher布局
    常用布局参考
    增加动画的效果
    AlertDialog的写法
    自定义Toast
    适配器的经典写法
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074862.html
Copyright © 2011-2022 走看看