Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. // input: object -- node in a tree
  2. // output: number -- largest sum for a layer of the tree
  3. // 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
  4. // 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
  5. // return value, updating it as necessary.
  6.  
  7. const findLargestLevel = function(node) {
  8. let highestLayer = node.value;
  9. if (node.children) {
  10. let layerTotal = 0;
  11. node.children.forEach(child => {
  12. layerTotal += child.value;
  13. });
  14. highestLayer = layerTotal > highestLayer ? layerTotal : highestLayer;
  15. sumChildren(node.children);
  16. }
  17.  
  18. function sumChildren(arr) {
  19. let layerTotal = 0;
  20. arr.forEach(node => {
  21. if (node.value) {
  22. layerTotal += node.value;
  23. }
  24. });
  25. highestLayer = layerTotal > highestLayer ? layerTotal : highestLayer;
  26. let nextArr = arr.map(node => {
  27. if (node.children) {
  28. return node.children;
  29. }
  30. });
  31. if (nextArr.length) {
  32. sumChildren(nextArr);
  33. }
  34. }
  35. return highestLayer;
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement