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

187
Views
Finding a value in a Binary Search Tree

I am making the code of a function to find a value passed by parameter in a BinarySearchTree but it is not working for me and I don't know why.if the price is inside the tree I have to return true, if the price passed by parameter is less than or equal to 0 I have to return "error" and if it is not found I must return false this is my code.

BinarySearchTree.prototype.searchPrice = function (price) {

    if (price <= 0) return "Error"  
    
    if(this.value === price) return true;

    if(this.value < price) return this.right.searchPrice(price);

    if(this.value > price) return this.left.searchPrice(price);

    if(this.value === null) return false;
};
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The issue might be that you have null check for this.value at the end which causes the if(this.value < price) always to be true when this.value is null

Try to move the line if(this.value === null) return false; at the top and see if it works

UPDATE: Also you need to add null checks for the this.left and this.right

BinarySearchTree.prototype.searchPrice = function (price) {

    if (price <= 0) return "Error"  

// move this line at the top like this
    if(this.value === null) return false;
    
    if(this.value === price) return true;

    if(this.value < price) {
        if(!this.right) {
            return false;
        }
        return this.right.searchPrice(price);
    }

    if(this.value > price){
        if(!this.left) {
            return false;
        }
        return this.left.searchPrice(price);
    }

};
about 4 years ago · Santiago Gelvez 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!