一時興起參加了 LeetCode 的 Weekly Contest #40,用Javascript只解出了第一題計算二元樹每層平均值,思維是用兩個陣列,一個存每層的平均,一個存每層的總數量,最後相除得到每層的平均,實作如下:

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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/

var averageOfLevels = function(root) {
var sumArr = [];
var countArr = [];
var sum = function(node, level) {
if (!node) return
if (!sumArr[level]) sumArr[level] = 0;
sumArr[level] += node.val;
if (!countArr[level]) countArr[level] = 0;
countArr[level]++;
sum(node.left, level + 1);
sum(node.right, level + 1);
}

sum(root, 0);
var meanArr = sumArr.map((sum, level) => sum / levelCountArr[level]);
return meanArr;
};