Guest User

Untitled

a guest
Feb 21st, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. //OICE
  2. //I: Binary tree: array of objects with a value, length and children property.
  3. //O: The level which has the largest summed value;
  4. //C: -
  5. //E: -
  6.  
  7. //We are going to create a modified version of the binary tree that should expedite this process for us.
  8. //We each level, we will also have a level property on the node that will allow us to eval deeply nested
  9. //But far separated nodes on the same level.
  10.  
  11. const ModBinaryTree = (value, level = 0) => {
  12. this.value = value;
  13. this.level = level;
  14. this.children = [];
  15. };
  16. //This would be a very straight forward addition to a binary tree as you could just base the next recursive call's
  17. //level children's level value +1 on the current.
  18. //Then we can find the sum of each level
  19.  
  20. const findLargestLevel = (tree) => {
  21. let levelSumObj = {};
  22. let largest = [0,0];
  23. (function walkThatTree(arrOfNodes) {
  24. if (arrOfNodes !== undefined) {
  25. let sumNode = arrOfNodes.reduce((total, ele) => {
  26. total += ele.value;
  27. walkThatTree(ele.children);
  28. return total;
  29. }, 0);
  30. if (levelSumObj[arrOfNodes[0].level]) levelSumObj[arrOfNodes[0].level] += sumNode;
  31. else levelSumObj[arrOfNodes[0].level] = sumNode;
  32. }
  33. }(tree));
  34. for (let keys in levelSumObj) {
  35. if (levelSumObj[keys] > largest[1]) {
  36. largest[0] = keys;
  37. largest[1] = levelSumObj[keys]
  38. }
  39. }
  40. return largest[0];
Add Comment
Please, Sign In to add comment