Created
July 27, 2017 16:57
-
-
Save austinreuter/df30b7ed4f2f9d92dfbcb61f9a7ea081 to your computer and use it in GitHub Desktop.
largest level of tree
This file contains hidden or 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
//which children have the largest sum node values | |
//input: node | |
//output: level of tree | |
//use breadth first search, using a cue; first in last out; | |
//edge: in case of tie, use level closest to root. | |
//sum of children; | |
// upon each sum, update the sum to the larger sum; | |
//(since breadth first, recurse level by level;) | |
// could stop depth first recursion to find other branches with same level; | |
//(at each level combine the values of each child) | |
//each level of recursion, update findLargestLevel | |
// | |
//1 | |
//4 3 2 | |
//3 7 | |
const findLargestLevel = function(node) { | |
var value = node.value; | |
var children = node.children; | |
var largestSum = 0; | |
function depth(/**/) { | |
var sum = 0; | |
//TODO: selectively recurse, keep track of depth | |
children.forEach(function(child) { | |
sum += child.value; | |
}); | |
return sum; | |
} | |
depthSum = depth(); | |
if (depthSum > largestSum) { | |
largestSum = depthSum; | |
} | |
return largestSum; | |
}; | |
function Tree(value) { | |
this.value = value; | |
this.children = []; | |
} | |
var myTree = new Tree(1); | |
myTree.children.push(new Tree(4), new Tree(3), new Tree(2)); | |
myTree.children[0].children.push(new Tree(3)); myTree.children[2].children.push(new Tree(7)); | |
console.log(myTree) | |
findLargestLevel(myTree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment