# LeetCode: Average Of Levels In Binary Tree Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * Definition for a binary tree node.3 * function TreeNode(val, left, right) {4 *     this.val = (val===undefined ? 0 : val)5 *     this.left = (left===undefined ? null : left)6 *     this.right = (right===undefined ? null : right)7 * }8 */9/**10 * @param {TreeNode} root11 * @return {number[]}12 */13var averageOfLevels = function (root) {14  const average = arr => arr.reduce((acc, el) => acc + el, 0) / arr.length15  const valuesAtDepth = []16
17  const recursion = function (node, depth = 0) {18    if (!node) {19      return20    }21
22    if (!valuesAtDepth[depth]) {23      valuesAtDepth[depth] = []24    }25    valuesAtDepth[depth].push(node.val)26    recursion(node.left, depth + 1)27    recursion(node.right, depth + 1)28  }29
30  recursion(root)31
32  return valuesAtDepth.map(average)33}```

leetcode

tree

recursion

## Next Post

LeetCode: Intersection Of Two Linked Lists

Mar 5, 2021

Search Posts