2

I am implementing Binary Search Trees in JavaScript, but while writing the insert function, some error is occuring (most probably in the RECURSION).

Here is my code:

class BinarySearchTree {
  constructor() {
    this.length = 0;
    this.root = null;
  }
  insert(elem) {
    if (!this.root) {
      //If root is null then this is the root.
      this.root = new BSTNode(elem);
    } else {
      let newNode = new BSTNode(elem);
      let myRoot = this.getParent(this.root, elem)
      console.log(myRoot);

      if (myRoot[1] == 'left') myRoot[0].left = newNode;      //Error Line
      else myRoot[0].right = newNode;

      this.nodes.push(newNode);
      this.arr.push(elem);
    }
    this.length++
  }
  getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {
      if (root.left!==null) this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }
}
class BSTNode {
  constructor(val) {
    this.value = val;
    this.left = null; //Left Node
    this.right = null; //Right Node
  }
}

There are two classes; namely BinarySearchTree and BSTNode.

The Error:
Uncaught TypeError: Cannot read property '1' of undefined

I am unable to find the mistake.

Note that other solutions to do the same thing is also welcome.

1
  • Hello and welcome to StackOverflow, It says that myRoot is not defined yet! are you sure that myRoot is defined correctly? Commented Jun 14, 2020 at 18:12

2 Answers 2

1

you should return the result of this.getParent(root.left, elem); and this.getParent(root.right, elem);

getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {

      if (root.left!==null) return this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) return this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

It should be:

getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

    if (elem < root.value) {
      if (root.left!==null) return this.getParent(root.left, elem); 
      else return [root, 'left'];
    } else {
      if (root.right!==null) return this.getParent(root.right, elem);
      else return [root, 'right']
    }
  }

Without returing those values, it will do the work to find the node, but not return it. Most recurive functions return themselves, like: function foo(){return foo()}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.