1. var averageOfLevels = function (root) {
    2. if (!root) {
    3. return []
    4. }
    5. const resList = [root.val],
    6. countList = [1]
    7. // row记录层数,并作为数组下标,相同层数的数据存在一起
    8. const bfs = (node, row = 1) => {
    9. let sum = 0
    10. count = 0
    11. if (!node || (!node.left && !node.right)) return
    12. if (node.left) {
    13. count++
    14. sum += node.left.val
    15. }
    16. if (node.right) {
    17. count++
    18. sum += node.right.val
    19. }
    20. countList[row] = countList[row] ? countList[row] + count : count
    21. resList[row] = resList[row] ? resList[row] + sum : sum
    22. bfs(node.right, row + 1)
    23. bfs(node.left, row + 1)
    24. }
    25. bfs(root)
    26. for (let i = 0; i < resList.length; i++) {
    27. resList[i] = resList[i] / countList[i]
    28. }
    29. return resList
    30. };