# 637. Average of Levels in Binary Tree - LeetCode 原

yysue

## Solution

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;
}
}
}
``````

### yysue

Leetcode 637. Average of Levels in Binary Tree

xgnming
09/06
0
0
LeetCode笔记：637. Average of Levels in Binary Tree

Cloudox_
01/11
0
0
[leetcode]Binary Search Tree Iterator

question Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling will return the next smallest number in th......

NineRec
2015/08/27
0
0
[算法总结] 20 道题搞定 BAT 面试——二叉树

09/04
0
0
[LeetCode] Maximum Width of Binary Tree 二叉树的最大宽度

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structu......

2017/12/06
0
0

go4it
29分钟前
1
0
Ubuntu常用操作

hc321

1
0

1.首先我查看了一下是否自己的网络问题，通过对比其他资源的访问速度和下载速度，确认不是 2.通过ping 和 tracert 判断cdn域名能否正常访问，（最后回想感觉这一步可以省略，因为每次最终能访...

3
0
Mybatis 学习笔记四 MyBatis-Plus插件

Mybatis 学习笔记四 MyBatis-Plus插件 maven依赖 <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <ve......

5
0

3
0