Created
February 8, 2018 17:32
-
-
Save FermiDirak/fe0ac3307b7ef6fe146581845d6e1943 to your computer and use it in GitHub Desktop.
Largest Row in a Tree Solution
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
var Tree = function(value) { | |
this.value = value; | |
this.children = []; | |
} | |
Tree.prototype.addChild = function(value) { | |
this.children.push(new Tree(value)); | |
} | |
/** | |
* Returns the row with the largest sum of datum | |
* If theres a tie, return the closest row | |
*/ | |
Tree.prototype.findLargestLevel = function() { | |
var sumsByRow = {}; | |
var findLargestLevelHelper = function(level, tree) { | |
sumsByRow[level] = sumsByRow[level] || 0; | |
sumsByRow[level] += tree.value; | |
for (var i = 0; i < tree.children.length; i++) { | |
findLargestLevelHelper(level + 1, tree.children[i]); | |
} | |
} | |
findLargestLevelHelper(0, this); | |
var largestRow = -1; | |
var largestValue = -Infinity; | |
for (var row in sumsByRow) { | |
row = parseInt(row); | |
var value = sumsByRow[row]; | |
if (value > largestValue) { | |
largestRow = row; | |
} | |
} | |
return largestRow; | |
} | |
/** | |
* tests Find Largest Level if its working or not | |
*/ | |
var testFindLargestLevel = function() { | |
console.log('it should find the largest level of a tree'); | |
var tree = new Tree(5); | |
tree.addChild(3); | |
tree.addChild(6); | |
tree.children[0].addChild(13); | |
tree.children[0].addChild(8); | |
tree.children[1].addChild(6); | |
console.log(tree.findLargestLevel() === 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment