Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // You are given a binary tree whose nodes all have integer values
- //(both positive and negative).
- // Determine which level of the tree is the "largest"
- //i.e., you sum all the node values at that level,
- //and determine which level has the largest sum.
- // In the case of a tie, return the level closest to the root.
- const findLargestLevel = function(node) {
- // root is level 0
- // keep track of largestLvl
- // currentLvl
- // largestLvlSum
- // currentLvlSum
- // add the first node's value in lvlSum
- // update largestLvlSum and largestLvl if larger
- // iterate through node's children and recurse
- // return largestLvl
- let largestLvl = 0;
- let currentLvl = 0;
- let largestLvlSum = 0;
- function recurse(node) {
- if (node.next === null && currentLvl === 0) {
- return currentLvl;
- }
- if (node.next === null) {
- currentLvl--;
- return;
- }
- let lvlSum = 0;
- lvlSum += node.value;
- if (largestLvlSum < lvlSum) {
- largestLvlSum = lvlSum;
- largestLvl = currentLvl;
- }
- for (let i = 0; i < node.next.length; i++) {
- currentLvl++;
- recurse(node.next[i]);
- currentLvl--;
- }
- return largestLvl;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement