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;
};
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);
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.