Https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree

Tell us what’s happening:
What is wrong with my code?
Doesn’t pass last two cases.

Your code so far


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.set = new Set();
// change code below this line
// change code above this line
this.add = function(val)
{
  if (this.set.has(val))
  {
    return null;
  }

  new_node = new Node(val);
  if (this.root === null)
  {
    this.set.add(val);
    this.root = new_node;
    return ;
  }
  let current  = this.root;
  while (current)
  {
    if (val < current.value)
    {
      if (!current.val)
      {
        current.left = new_node;
        this.set.add(val);
        return ;
      }
      current = current.left;
    }
    else
    {
      if (!current.right)
      {
        this.set.add(val)
        current.right = new_node;
        return ;
      }
      current = current.right;
    }
  }
}
}

let preorder = function(root)
{
if (root)
{
  preorder(root.left);
  console.log(root.value);
  preorder(root.right);
}
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/83.0.4103.61 Chrome/83.0.4103.61 Safari/537.36.

Challenge: Add a New Element to a Binary Search Tree

Link to the challenge:

Hi @ishworii,

one reason is likely that it is not in the indicated place …

// change code below this line
// change code above this line