Recursive Solution for add a new element to Binary Search Tree

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);
        }
      }
    }
  }
}
1 Like

Hi @thonker86!

You might consider adding some ternary operators to some of these if/else statements.

var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
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){
        !root.left ? root.left = newNode : this.add(value, root.left);
      }else{
        !root.right ? root.right = newNode : this.add(value, root.right);
      }
    }
  }
}
2 Likes