Created
January 31, 2019 17:42
-
-
Save andrewgeorgemitchell/5c58b9a67e3d8a80e56144571cc7f524 to your computer and use it in GitHub Desktop.
A small function to find the sum of levels on a tree and return the level with the largest sum.
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
const findLargestLevel = function(node) { | |
// Search Breadth First | |
// Define queue | |
let queue = []; | |
// Enqueue first | |
let depth = 0; | |
queue.push({node, depth}); | |
// Track Depth Sums | |
let sumTracker = []; | |
while (queue.length > 0) { | |
let { node, depth } = queue.shift(); | |
// Queue Children | |
for (let i = 0; i < node.children.length; i++) { | |
queue.push({ | |
'node': node.children[i], | |
'depth': depth + 1, | |
}); | |
} | |
// Add to sumTracker to keep count | |
if (typeof sumTracker[depth] !== 'undefined') { | |
sumTracker[depth] = sumTracker[depth] + node.value; | |
} else { | |
sumTracker[depth] = node.value; | |
} | |
} | |
let currentLargestLevel = {}; | |
// Find largest level by iterating backwards | |
for (let i = sumTracker.length - 1; i >= 0; i--) { | |
if (i === sumTracker.length - 1 || sumTracker[i] >= currentLargestLevel.sum) { | |
currentLargestLevel = { | |
'sum': sumTracker[i], | |
'depth': i, | |
} | |
} | |
} | |
return currentLargestLevel; | |
}; | |
// | |
// Tests | |
// | |
// Build test tree | |
let nodeTwo3 = { | |
value: 10, | |
children: [ | |
] | |
} | |
let nodeTwo2 = { | |
value: 10, | |
children: [ | |
] | |
} | |
let nodeTwo1 = { | |
value: 10, | |
children: [ | |
] | |
} | |
let nodeOne2 = { | |
value: 10, | |
children: [ | |
nodeTwo1, | |
nodeTwo2, | |
] | |
} | |
let nodeOne1 = { | |
value: 10, | |
children: [ | |
nodeTwo3, | |
] | |
} | |
let root = { | |
value: 10, | |
children: [nodeOne1, nodeOne2] | |
} | |
console.log('level two should equal 30 and be largest:', findLargestLevel(root)); | |
nodeOne1.value = 25; | |
nodeOne2.value = 25; | |
console.log('level one should equal 50 and be largest:', findLargestLevel(root)); | |
root.value = 100; | |
console.log('level 0 should equal 100 and be largest:', findLargestLevel(root)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment