Created
May 16, 2021 01:32
-
-
Save CarlaTeo/91c2e296943a4f1f510b7889520c2238 to your computer and use it in GitHub Desktop.
[JS] Binary tree average level value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using BFS to solve | |
class Node { | |
constructor(data) { | |
this.data = data; | |
this.left = null; | |
this.right = null | |
} | |
} | |
function getBinaryTreeLevelsAverage(head) { | |
let currentLevel = 0; | |
const queue = [[head, currentLevel]]; | |
let levelSum = 0; | |
let levelNodeCount = 0; | |
const averages = []; | |
while(queue.length > 0) { | |
const [node, level] = queue.shift(); | |
if(level === currentLevel) { | |
levelNodeCount++; | |
levelSum += node.data; | |
} | |
else { | |
const average = levelSum / levelNodeCount; | |
averages.push(average); | |
currentLevel = level; | |
levelSum = node.data; | |
levelNodeCount = 1; | |
} | |
if(node.left) queue.push([node.left, currentLevel + 1]); | |
if(node.right) queue.push([node.right, currentLevel + 1]); | |
} | |
averages.push(levelSum / levelNodeCount); | |
return averages; | |
} | |
// ---------------------------------- Testing ---------------------------------------------------------- // | |
const head = new Node(4); | |
const node7 = new Node(7); | |
const node9 = new Node(9); | |
const node10 = new Node(10); | |
const node2 = new Node(2); | |
const node6 = new Node(6); | |
const node6b = new Node(6); | |
const node2b = new Node(2); | |
head.left = node7; | |
head.right = node9; | |
node7.left = node10; | |
node7.right = node2; | |
node2.right = node6b; | |
node6b.left = node2b; | |
node9.right = node6; | |
// 4 | |
// / \ | |
// 7 9 | |
// / \ \ | |
// 10 2 6 | |
// \ | |
// 6 | |
// / | |
// 2 | |
console.log(getBinaryTreeLevelsAverage(head)); // [ 4, 8, 6, 6, 2 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment