Diegohp141
Diegohp141

Reputation: 219

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;
};

Upvotes: 1

Views: 578

Answers (1)

Irakli Tchedia
Irakli Tchedia

Reputation: 277

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);
    }

};

Upvotes: 1

Related Questions