「每日LeetCode」2020年12月15日

本文最后更新于:2023年3月19日 晚上

Lt637. 二叉树的层平均值

637. 二叉树的层平均值

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

1
2
3
4
5
6
7
8
9
输入:
3
/ \
9 20
/ \
15 7
输出:[3, 14.5, 11]
解释:
0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。

提示:

  • 节点值的范围在 32 位有符号整数范围内。

思路

同二叉树的层次遍历,层次遍历的时候求每层的和,结束遍历之后用和除数组长度即为平均值加入结果数组中即可。

解答

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) {
const res = [];
const queue = [];
queue.push(root);
while (queue.length) {
const temp = queue.splice(0, queue.length);
let sum = 0;
let length = temp.length;
while (temp.length) {
let node = temp.shift();
sum += node.val;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res.push(sum / length);
}
return res;
};