Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!