Data Structures - Check if an Element is Present in a Binary Search Tree

I’m going to have to put this down to a problem with the test suite unless someone tells me otherwise. (tests failing).
But this way i will be copy-pasting the answer from the ‘hint’ in order to pass the test. i’ll make sure i understand the alternative (from ‘hint’), but we were advised to use the recursive nature of BST’s and some of these hints don’t seem to do that, and fail solutions that do.

  **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.isPresent = function(value, node=this.root){
  if(!node){return false}
  if(value === node.value){return true}
  else{
    if(value < node.value && node.left){
      return this.isPresent(value, node.left)
    }else if(value > node.value && node.right){
      return this.isPresent(value, node.right)
    }
  }
  return false
} 
// Only change code above this line
// added for testing: 
this.add=function(value){
  const newNode = new Node(value)
  if(this.root === null) { this.root = newNode }
  else{
    this.insertNode(this.root, newNode)
  }
}
this.insertNode=function(node, newNode) {
  if(newNode.value < node.value){
    if(!node.left){node.left = newNode}
    else{
      this.insertNode(node.left, newNode)
    }
  }else{
    if(!node.right){node.right = newNode}
    else{
      this.insertNode(node.right, newNode)
    }
  }
}
}
let tree = new BinarySearchTree()
tree.add(3)
tree.add(5)
tree.add(2)
tree.add(1)
console.log(tree)
console.log(tree.isPresent(11))
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36

Challenge: Data Structures - Check if an Element is Present in a Binary Search Tree

Link to the challenge:

edit: apologies, needed to update some minor code error, and it seems to work now!

sorry

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