javascript - 为什么在尝试搜索二叉树时出现无限循环?
问题描述
我在树中插入了数字。我使用 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";
}
}
解决方案
您的代码很好,您只是在 get() 方法的底部错误地进行了相等检查。您正在检查节点对象本身是否与传入的值相等,而不是它的 .val 属性。
你写了:
if(current === val){
return current;
}
什么时候需要:
if(current.val === val){
return current;
}
推荐阅读
- android - 使用片段测试的片段测试错误:无法实例化检测
- c++ - C++ - Why isn't the unicode output correct?
- cloud - 如何确保谷歌计算引擎上的防篡改/防篡改启动盘?
- sql - T-SQL query to summarize sales for ALL YEARS: with total per month per year, and cumulative monthly amounts
- pyspark - PySpark - Inseroverwrite - 文件已存在异常
- django - ImportError: cannot import name 'python_2_unicode_compatible' when running migrations for Django-Invitations
- python - Assign group to consecutive 1s in a Pandas Column
- flutter - How to open flutter plugins at Xcode?
- colors - 反转材质内部的颜色(UE4)?
- java - 我应该传递参数还是将它们注入到需要它们的地方?