I tried to create the insert
method for a binary search tree, but 'this.root' remains null
.
My logic is:
As long as current
(which at the beginning is this.root
) is not null
, continue to update the current
variable, by comparing it with the value we want to insert (if it's greater or less).
When current
is null
, we assign it the new Node:
class Node {
constructor(value){
this.value = value
this.left = null
this.right = null
}
}
class BST {
constructor(){
this.root = null
this.count = 0
}
insert(value){
this.count++
let current = this.root;
while(current){
if(value<current){
current=current.left
}
if(value>current){
current=current.right
}
}
current = new Node(value);
}
}
let Binst = new BST(10);
Binst.insert(22)
Binst.insert(12)
Binst.insert(4)
console.log(Binst)