freeCodeCamp Challenge Guide: Add a New Element to a Binary Search Tree

Add a New Element to a Binary Search Tree

This is a stub. Help the community by making a suggestion of a hint and/or solution. We may use your suggestions to update this stub.


Problem Explanation

This summarizes what need to be done without just restating the challenge description and/or instructions. This is an optional section

Relevant Links


Hints

Hint 1

Hint goes here

Hint 2

Hint goes here


Solutions

Solution 1 (Click to Show/Hide)
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;
  // change code below this line
  this.add = function (integer) {

    let curr = this.root;

    if (!curr) {
      this.root = new Node(integer);
      return undefined;
    };
    
    while (curr) {
      if (integer < curr.value) {
        if (!curr.left) {
          curr.left = new Node(integer);
          return undefined;
        }
        curr = curr.left;
      }
      else if (integer > curr.value) {
        if (!curr.right) {
          curr.right = new Node(integer);
          return undefined;
        }
        curr = curr.right;
      }
      else return null;
    }
  }   
}

Code Explanation

  • Code explanation goes here

Relevant Links