Skip to content

Instantly share code, notes, and snippets.

@zzandland
Created October 11, 2018 16:48
Show Gist options
  • Save zzandland/bc10368f2222db5c2e868dca6cf95bbd to your computer and use it in GitHub Desktop.
Save zzandland/bc10368f2222db5c2e868dca6cf95bbd to your computer and use it in GitHub Desktop.
Largest level of tree
var findLargestLevel = (node) => {
// make levelObj as closure var
const levelObj = {};
// inner function takes in node and level
const innerFunc = (node, level) => {
// if levelObj doesn't have property at this level
if (levelObj[level] === undefined) {
// create a new value, with the node inside an array
levelObj[level] = [node];
// otherwise
} else {
// concat the current node into the array
levelObj[level] = levelObj[level].concat(node);
}
// if left node != undefined
if (node.left !== undefined) {
// recurse into the left node, with level incremented
innerFunc(node.left, level + 1);
}
// if right node != undefined
if (node.right !== undefined) {
// recurse into the right node, with level incrementd
innerFunc(node.right, level + 1);
}
}
// initial invocation with root and level as 0
innerFunc(node, 0);
// make largestLevel var as [value, level]
let largestLevel = [0, 0];
// for level in levelObj
for (level in levelObj) {
// reduce each level's value (array) into sum
if (levelObj[level].length === 1) {
var sum = levelObj[level][0].value;
} else {
var sum = levelObj[level].reduce((a, b) => {
return a.value + b.value;
});
}
// if the reduced sum is greater than largestLevel[0] value,
if (sum > largestLevel[0]) {
// update the largestLevel array
largestLevel = [sum, Number(level)];
}
}
// return the largestLevel's level (second index)
return largestLevel[1];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment