Problem in Binary Search Tree

Tell us what’s happening:
I was studying Binary Search Tree in Data Structures. I am facing problem. In the while loop , the first condition(if(value > current.value)) , when I reassign current to current.right , current become undefined. Please someone tell me why it’s happening?

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(value){
  let newNode = new Node(value)
  if(!this.root){
    this.root = newNode
    return undefined
  }
  let current = this.root;
  while(current){
    if(value > current.value){
      if(current.right === null){
        current.right = newNode
        return undefined
      }
      current = current.rigth
    }
    if(value < current.value){
      if(current.left === null){
        current.left = newNode
        return undefined
      }
      current= current.left
    }
    if(value === current.value){
      return null
    }
  }

}
// Only change code above this line
}

Your browser information:

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

Challenge: Add a New Element to a Binary Search Tree

Link to the challenge:

Maybe because you have misspelt right in the code as rigth?

1 Like

Oops… Sorry lol😂… Silly mistake… Thanks

1 Like

He he! No problem. And it passed the tests with the typo fixed, so that’s great.

1 Like