637. Average of Levels in Binary Tree - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了637. Average of Levels in Binary Tree - LeetCode相关的知识,希望对你有一定的参考价值。

Question

637.?Average of Levels in Binary Tree
技术分享图片

Solution

思路:定义一个map,层数作为key,value保存每层的元素个数和所有元素的和,遍历这个树,把map里面填值,遍历结束后,再遍历这个map,把每层的平均数放到数组里,最后数组转为list返回,不用考虑list里的排序了.

Java实现:

/**
 * 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) {
        
        Map<Integer, TreeLevel> store = new HashMap<>();
        init(root, store, 1);
        Double[] arr = new Double[store.size()];
        for (Map.Entry<Integer, TreeLevel> entry : store.entrySet()) {
            arr[entry.getKey() - 1] = entry.getValue().getAverage();
        }
        return Arrays.asList(arr);
    }
    
    void init(TreeNode root, Map<Integer, TreeLevel> store, int level) {
        if (root == null) return;
        TreeLevel treeLevel = store.get(level);
        if (treeLevel == null) {
            treeLevel = new TreeLevel();
            store.put(level, treeLevel);
        }
        treeLevel.count++;
        treeLevel.sum+=root.val;
        init(root.left, store, level+1);
        init(root.right, store, level+1);
    }
    
    // 定义一个类存储每一层的信息
    class TreeLevel {
        int count; // 该层有多少元素
        double sum; // 该层所有元素的和,这个要用double类型来保存,eg:[2147483647,2147483647,2147483647]
        
        // 返回该层的平均数
        Double getAverage() {
            return sum / count;
        }
    }
}

以上是关于637. Average of Levels in Binary Tree - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

LeetCode - 637. Average of Levels in Binary Tree

[leetcode-637-Average of Levels in Binary Tree]