首页 > 解决方案 > 为什么在尝试搜索二叉树时出现无限循环?

问题描述

我在树中插入了数字。我使用 get 查看该数字是否存在(知道它存在)并且 google chrome 崩溃,因为它无限循环。我已经多次查看代码,但我无法弄清楚为什么它不起作用。请帮忙。

我在控制台中的命令:

 tree = new BinaryTree;

 tree.insert(15);
 tree.insert(23);
 tree.insert(6);

ETC...

 tree.get(55); 

谷歌浏览器崩溃NOOOOOOO崩溃

class Node {
    constructor(val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class BinaryTree {
    constructor(){
        this.root = null;
    }

    insert(val){
        var newNode = new Node(val);
        if (this.root){
            var current = this.root
            while(true) {
            if(val < current.val){
                if(current.left === null){
                    current.left = newNode;
                    return current;
                }
                current = current.left;
            }
            if(val > current.val){
                if(current.right === null){
                    current.right = newNode;
                    return current; 
                }
                current = current.right;
            }
            if(val === current.val){
                return "already exists";
            }
        }
    }
    this.root = newNode;
    return this;
}

    get(val) {

        if(this.root){
            var current = this.root;
            while(true){
                if (val < current.val){
                    if(current.left == null){
                        return "does not exist";
                    }
                    current = current.left;
                }
                if (val > current.val){
                    if(current.right == null){
                        return "does not exist";
                    }
                    current = current.right;
                }
                 if(current === val){
                        return current;
               } 
            }
        }
        return "tree is empty";
    }
}

标签: javascriptbinary-tree

解决方案


您的代码很好,您只是在 get() 方法的底部错误地进行了相等检查。您正在检查节点对象本身是否与传入的值相等,而不是它的 .val 属性。

你写了:

if(current === val){
    return current;
}

什么时候需要:

if(current.val === val){
    return current;
}

推荐阅读