I am working on a Binary search tree and have a problem while adding the values to the tree. When I add values(numbers) in order (descending or ascending) they are added in the right positions, but if I add value that is supposed to go somewhere in between values that are already in the tree, they don't get sorted. you can see that in the picture, the number [ 3 ] is added after 1, but it should be between [ 4 ] and [ 1 ] So the question is, what exactly am I doing wrong and how to fix it
I am adding my code for the add function below the picture
The Node object
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;
}
}
How I call the add function
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);
the output of console.log(bst);



elseelseparts, which have noifbefore.ifExistsas well.