Home > Software design >  How to sum left nodes from binary tree javascript
How to sum left nodes from binary tree javascript

Time:12-04

I have a binary tree, and I want to sum all the left-most nodes. So

         2
        / \
       7   5
      / \ / \
     2  6    9  

Taking that tree, I want the result to be 11, because I want to sum 2 7 2.

So I tried doing it like so:

function leftmostNodesSum(array) {
  let sum = 0;
  let currentNode = array[0];
  let previousNode;
  for (let i = 0; i < array.length; i  ) {
    if (i === currentNode * 2   1) {
      previousNode = currentNode;
      currentNode = array[i];
      sum  = previousNode;
    }
  }
  return sum;
}

I have to say that I have my array with a "breadth-first" format, so my first node has the index 0 in my array, and the left nodes are 2n 1. The array looks like so: [2, 7, 5, 2, 6, 0, 9] The number 0 represents an empty node.

I'm kinda new to this so I would appreciate your help, any idea?

CodePudding user response:

function leftmostNodesSum(array) {
  let sum = 0;
  let currentNode = 0;
  for (let i = 0; i < array.length; i  ) {        
    if (i === currentNode) {          
      sum  = array[i];
      currentNode = 2 * i   1;
    }
    
  }
  return sum;
}
  • Related