Data Structures - Add a New Element to a Binary Search Tree

Tell us what’s happening:
Describe your issue in detail here.

I am not able to digest, knowing the fact that i am able to initialiase root, root.left or root.right without defining the root variable. root is only define to use as an instance variable of an object in a constructor function.
Please somebody help me to clear my concept.

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;
  // Only change code below this line
  this.add = function(ele){
    let node = new Node(ele);
      this.root = node;
    else {
  this.insert = function(root,newNode){
        return null;
      else if(newNode.value < root.value){
        if(!root.left) {
         root.left = newNode;
        } else {
     else if(newNode.value > root.value){
       if(!root.right) {
         root.right = newNode;
       } else {
  // Only change code above this line

let bst = new BinarySearchTree();


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Data Structures - Add a New Element to a Binary Search Tree

Link to the challenge:

  • this is where Node constructor is being called, and which means it will have “left, right, value” properties

does that cleat things up a bit?

happy coding :slight_smile:

function Binary() {
  this.root = null;
  root = 'hello';

let b = new Binary();

What will you say about this???

what do you see in console when you run this?

if constructor functions are something that you need to work with then you can read about them that will give you more in depth info about how to use them in your code.

happy reading :slight_smile:

I hope this explanation can help a bit:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.