我在树上插入了数字。我使用get来查看该数字是否存在(知道确实存在),并且由于其无限循环,google chrome崩溃了。我已经遍历了多次代码,我不知道为什么它不起作用。请帮忙。
我在控制台中的命令:
tree = new BinaryTree;
tree.insert(15);
tree.insert(23);
tree.insert(6);
等...
tree.get(55);
Google Chrome崩溃 NOOOOOO 崩溃
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";
}
}
答案 0 :(得分:1)
您的代码很好,您很容易在get()方法的底部进行错误的相等检查。您正在检查节点对象本身是否与传递的值相等,而不是其.val属性。
您写道:
if(current === val){
return current;
}
何时需要:
if(current.val === val){
return current;
}
答案 1 :(得分:0)
您的代码永远不会超出while循环的范围
while(true) {
if(val < current.val){
if(current.left === null){
current.left = newNode;
return current;
}
current = current.left;
}
}
white(true)
将始终为true,因此如果您不退出循环,它将无限运行,所以我猜测是出于某种原因
current.left === null
永远不是真的