LeetCode: Average Of Levels In Binary Tree Solution

1/**
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} root
11 * @return {number[]}
12 */
13var averageOfLevels = function (root) {
14 const average = arr => arr.reduce((acc, el) => acc + el, 0) / arr.length
15 const valuesAtDepth = []
16
17 const recursion = function (node, depth = 0) {
18 if (!node) {
19 return
20 }
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}

Comments

Loading comments...

Tags

leetcode

tree

recursion

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Intersection Of Two Linked Lists

Mar 5, 2021

Previous Post

HoningJS

Search Posts