简体   繁体   English

在二叉搜索树中查找值

[英]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 中的参数传递的值,但它对我不起作用,我不知道为什么。如果价格在树内,我必须返回 true,如果价格通过通过参数小于或等于 0 我必须返回“错误”,如果没有找到我必须返回 false 这是我的代码。

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问题可能是您最后对this.value进行了null检查,这导致if(this.value < price)this.valuenull时始终为true

Try to move the line if(this.value === null) return false;尝试移动线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更新:您还需要为this.leftthis.right添加null检查

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

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM