Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. // You are given a binary tree whose nodes all have integer values
  2. //(both positive and negative).
  3.  
  4. // Determine which level of the tree is the "largest"
  5. //i.e., you sum all the node values at that level,
  6. //and determine which level has the largest sum.
  7.  
  8. // In the case of a tie, return the level closest to the root.
  9.  
  10. const findLargestLevel = function(node) {
  11. // root is level 0
  12. // keep track of largestLvl
  13. // currentLvl
  14. // largestLvlSum
  15. // currentLvlSum
  16. // add the first node's value in lvlSum
  17. // update largestLvlSum and largestLvl if larger
  18. // iterate through node's children and recurse
  19. // return largestLvl
  20.  
  21. let largestLvl = 0;
  22. let currentLvl = 0;
  23. let largestLvlSum = 0;
  24.  
  25. function recurse(node) {
  26. if (node.next === null && currentLvl === 0) {
  27. return currentLvl;
  28. }
  29.  
  30. if (node.next === null) {
  31. currentLvl--;
  32. return;
  33. }
  34.  
  35. let lvlSum = 0;
  36. lvlSum += node.value;
  37.  
  38. if (largestLvlSum < lvlSum) {
  39. largestLvlSum = lvlSum;
  40. largestLvl = currentLvl;
  41. }
  42.  
  43. for (let i = 0; i < node.next.length; i++) {
  44. currentLvl++;
  45. recurse(node.next[i]);
  46. currentLvl--;
  47. }
  48.  
  49. return largestLvl;
  50. }
  51.  
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement