Created
November 14, 2019 17:24
-
-
Save f3lixding/56a89ad11bba36d828528966eb3cdc47 to your computer and use it in GitHub Desktop.
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
// assuming the node has the following structure: | |
class Node { | |
constructor(value) { | |
this.val = value; | |
this.children = []; | |
} | |
addNode(val) { | |
if (typeof val === 'number') { | |
this.children.push(new Node(val)); | |
} else if (val.constructor === Node) { | |
this.children.push(val); | |
} else { | |
throw ('input type must be either number or node'); | |
} | |
} | |
} | |
// general strategy: | |
// traverse down the tree in a level order fashion | |
// whilst keepting track of the level we are currently scanning through | |
// keep track of the max sum we have encountered so far | |
// in the event we come across a sum greater than what is specified by the max | |
// we over write the max level and the sum associated with it | |
// we do this until we have exhausted all levels. | |
// we return the level on record; | |
var findLargestLevel = function(root) { | |
var level = 0; | |
var maxLevel; | |
var maxSum = Number.MIN_VALUE; | |
var queue = [root]; | |
while (queue.length) { | |
level += 1; | |
var curLevelLength = queue.length; | |
var curSum = 0; | |
while(curLevelLength--) { | |
var curNode = queue.shift(); | |
curSum += curNode.val; | |
for (var i = 0; i < curNode.children.length; i++) { | |
queue.push(curNode.children[i]); | |
} | |
} | |
if (curSum > maxSum) { | |
maxSum = curSum; | |
maxLevel = level; | |
} | |
} | |
return maxLevel; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment