Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum left nodes from binary tree javascript

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?

like image 717
Lordkaito Avatar asked Nov 20 '25 19:11

Lordkaito


1 Answers

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;
}
like image 60
Siddharth Seth Avatar answered Nov 22 '25 10:11

Siddharth Seth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!