Continuing the discussion from freeCodeCamp Challenge Guide: Add a New Element to a Binary Search Tree:
Recursive Solution for the challenge
Solution 2 (Recursive)
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.add = (value, root = this.root)=>{
let newNode = new Node(value);
if(!this.root){
this.root = newNode;
}else{
if(value == root.value){
return null;
}else if(value < root.value){
if(!root.left){
root.left = newNode;
}else{
return this.add(value, root.left);
}
}else{
if(!root.right){
root.right = newNode;
}else{
return this.add(value, root.right);
}
}
}
}
}