code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

637 Average Of Levels In Binary Tree

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val) {
  this.val = val
  this.left = this.right = null
}

const averageOfLevelsInBinaryTree = root => {
  let result = []
  let queue = [root]
  while (queue.length !== 0) {
    let tempQueue = []
    const size = queue.length
    for (let i = 0; i < size; i++) {
      const node = queue.shift()
      tempQueue.push(node.val)
      if (node.left) {
        queue.push(node.left)
      }
      if (node.right) {
        queue.push(node.right)
      }
    }
    result.push(tempQueue.reduce((a, t) => (t += a), 0) / tempQueue.length)
  }
  return result
}

test('averageOfLevelsInBinaryTree', () => {
  const t1 = new TreeNode(3)
  t1.right = new TreeNode(20)
  t1.left = new TreeNode(9)
  t1.right.left = new TreeNode(15)
  t1.right.right = new TreeNode(7)
  expect(averageOfLevelsInBinaryTree(t1)).toEqual([3, 14.5, 11])
})

Created 2020-12-07T13:58:23+05:30 · Edit