Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // input: object -- node in a tree
- // output: number -- largest sum for a layer of the tree
- // alg: look at the given node and set the return value to its value. then sum its children, if the children sum to more than the value of the node, set
- // the return value to their sum. recursively call on the children of the children in the current level summing them and determining if their sum is higher than the
- // return value, updating it as necessary.
- const findLargestLevel = function(node) {
- let highestLayer = node.value;
- if (node.children) {
- let layerTotal = 0;
- node.children.forEach(child => {
- layerTotal += child.value;
- });
- highestLayer = layerTotal > highestLayer ? layerTotal : highestLayer;
- sumChildren(node.children);
- }
- function sumChildren(arr) {
- let layerTotal = 0;
- arr.forEach(node => {
- if (node.value) {
- layerTotal += node.value;
- }
- });
- highestLayer = layerTotal > highestLayer ? layerTotal : highestLayer;
- let nextArr = arr.map(node => {
- if (node.children) {
- return node.children;
- }
- });
- if (nextArr.length) {
- sumChildren(nextArr);
- }
- }
- return highestLayer;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement