var averageOfLevels = function (root) {
if (!root) {
return []
}
const resList = [root.val],
countList = [1]
// row记录层数,并作为数组下标,相同层数的数据存在一起
const bfs = (node, row = 1) => {
let sum = 0
count = 0
if (!node || (!node.left && !node.right)) return
if (node.left) {
count++
sum += node.left.val
}
if (node.right) {
count++
sum += node.right.val
}
countList[row] = countList[row] ? countList[row] + count : count
resList[row] = resList[row] ? resList[row] + sum : sum
bfs(node.right, row + 1)
bfs(node.left, row + 1)
}
bfs(root)
for (let i = 0; i < resList.length; i++) {
resList[i] = resList[i] / countList[i]
}
return resList
};