-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.js
40 lines (37 loc) · 972 Bytes
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
// 找到每一层的平均值
// 最直接的实现是层序遍历(BFS)
// 其实DFS也行
function getLevelSequence (nodes, sequences) {
const values = [];
const nextLevelNodes = nodes.reduce((arr, node) => {
values.push(node.val);
node.left && arr.push(node.left);
node.right && arr.push(node.right);
return arr;
}, []);
sequences.push(values.reduce((sum, val) => {
sum += val;
return sum;
}, 0) / nodes.length);
if (nextLevelNodes.length) {
return getLevelSequence(nextLevelNodes, sequences);
}
}
var averageOfLevels = function (root) {
const firstLevelNodes = [
root, ];
const sequences = [];
getLevelSequence(firstLevelNodes, sequences);
return sequences;
};