Skip to content

Instantly share code, notes, and snippets.

@basekays
Created February 23, 2017 17:53
Show Gist options
  • Select an option

  • Save basekays/9000c1587879cc8376b9669f5ffc1e01 to your computer and use it in GitHub Desktop.

Select an option

Save basekays/9000c1587879cc8376b9669f5ffc1e01 to your computer and use it in GitHub Desktop.
// helper function to get sum of the level array;
var sumOfLevel = function(levelArray) {
var sum = levelArray[0];
for (var i = 1; i < levelArray.length; i++) {
sum += levelArray[i];
}
return sum;
}
var compareSums = function(array) {
var biggestSum = array[0];
for (var i = 1; i < array.length; i++) {
if (biggestSum < array[i]) {
biggestSum = array[i];
}
}
return biggestSum;
}
var findLargestLevel = function(node) {
var totalSum = [];
var firstLevelSum = node.value;
totalSum.push(firstLevelSum);
// goal: 1) check if node has children nodes 2) if it has children node, add them into the chlidren array of that level;
// 1) checking if children nodes are present
if (node.children.length) {
var nextLevelChildren = [];
for (var i = 0; i < node.children.length; i++) {
// 2) add them into the children array
nextLevelChildren.push(node.children[i]);
}
// 3) getting sum of that level using sumOfLevel (defined above)
var nextLevelSum = sumOfLevel(nextLevelChildren);
totalSum.push(nextLevelSum);
// recurse
for (var i = 0; i < nextLevelChildren.length; i++) {
findLargestLevel(nextLevelChildren);
}
}
// compare level's sums
return compareSums(totalSum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment