代码仓库:Github | Leetcode solutions @doubleZ0108 from Peking University.
- 解法1(JS T15.33% S9%):还是正常树的层序遍历,现将每个节点的值都保存在对应层级的数组中,然后再用数组的map()方法将每一层的数组求平均值
- 注意添加左右节点的时候是对node来说的,不要递归写多了都成root的左右节点反复加了
var averageOfLevels = function(root) {
var res = [];
var queue = [[root, 1]];
while (queue.length) {
var data = queue.shift();
var node=data[0], level=data[1];
if (res.length < level) {
res.push([node.val]);
} else {
res[level-1].push(node.val);
}
if (node.left) {
queue.push([node.left, level+1]);
}
if (node.right) {
queue.push([node.right, level+1]);
}
}
return [...res.map(x => _.sum(x)/x.length)];
};
该文章介绍了一种使用层序遍历解决二叉树各层节点平均值问题的方法。通过存储节点及其层级,确保正确添加左右子节点,并避免重复添加。最后,利用数组映射功能计算每层平均值。
252

被折叠的 条评论
为什么被折叠?



