【发布时间】:2018-09-22 16:36:22
【问题描述】:
我正在研究二叉搜索树,在向树中添加值时遇到问题。 当我按顺序(降序或升序)添加值(数字)时,它们被添加到正确的位置,但是如果我添加的值应该位于树中已经存在的值之间的某个位置,它们不会被排序。可以看到图中,数字[3]加在1之后,但是应该在[4]和[1]之间 所以问题是,我到底做错了什么以及如何解决它
我正在为图片下方的添加功能添加我的代码
节点对象
function Node(data){
this.data=data;
this.left=null;
this.right=null;}
function BinarySearchTree(){
this.root = null;
var current=null;
var newNode=null;
this.add = function(data){
var root = this.root;
if(!root){
this.root= new Node(data);
return;
}else{
if(this.ifExists(data)){
}else{
current=root;
newNode= new Node(data);
while(current){
if(data<current.data){
if(!current.left){
current.left=newNode;
break;
}else{
current= current.left;
}
}else{
if(!current.right){
current.right=newNode;
break;
}else{
current=current.right;
}
}
}
}
}
}
}
this.ifExists=function(data){
var current = this.root;
// console.log(current);
while(current){
if(data==current.data){
return true;
}
current = data < current.value ? current.left : current.right;
}
return false;
}
}
如何调用 add 函数
var bst= new BinarySearchTree();
bst.add(7);
bst.add(8);
bst.add(4);
bst.add(1);
bst.add(15);
bst.add(67);
bst.add(9);
bst.add(3);
console.log(bst);
console.log(bst)的输出;
【问题讨论】:
-
你有一些
elseelse部分,之前没有if。 -
@NinaScholz 错误地将代码复制到 stackoverflow 中,只是修复了代码。但这不是问题
-
我不明白这个问题。您将 3 标记为错误的位置,但 1 应该是左孩子,因为它小于 4。3 应该是右孩子。
-
您应该添加mvce,以便清楚问题出在哪里。如果我添加缺少的代码以使其运行,它可以正常工作。我得到了一个有效的 bst。
-
请添加缺少的部分,例如
ifExists。
标签: javascript sorting binary-search-tree