freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree.english.md
Randell Dawson c25fa49b5b fix(curriculum): changed test text to use should for Coding Interview Prep - part 1 of 2 (#37765)
* fix: changed test text to use should

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: use singular of verb

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: changed punctuation

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: reworded test text

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>
2019-11-19 20:13:45 -05:00

4.8 KiB

id, title, challengeType, forumTopicId
id title challengeType forumTopicId
587d8257367417b2b2512c7b Add a New Element to a Binary Search Tree 1 301618

Description

Now that we have an idea of the basics lets write a more complex method. In this challenge, we will create a method to add new values to our binary search tree. The method should be called add and it should accept an integer value to add to the tree. Take care to maintain the invariant of a binary search tree: the value in each left child should be less than or equal to the parent value, and the value in each right child should be greater than or equal to the parent value. Here, let's make it so our tree cannot hold duplicate values. If we try to add a value that already exists, the method should return null. Otherwise, if the addition is successful, undefined should be returned. Hint: trees are naturally recursive data structures!

Instructions

Tests

tests:
  - text: The <code>BinarySearchTree</code> data structure should exist.
    testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() }; return (typeof test == 'object')})());
  - text: The binary search tree should have a method called <code>add</code>.
    testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; return (typeof test.add == 'function')})());
  - text: The add method should add elements according to the binary search tree rules.
    testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== 'function') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); const expectedResult = [ 1, 4, 7, 8, 34, 45, 73, 87 ]; const result = test.inOrder(); return (expectedResult.toString() === result.toString()); })());
  - text: Adding an element that already exists should return <code>null</code>.
    testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== 'function') { return false; }; test.add(4); return test.add(4) == null; })());

Challenge Seed

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
  // change code above this line
}

After Test

BinarySearchTree.prototype = {
  isBinarySearchTree() {
    if (this.root == null) {
      return null;
    } else {
      var check = true;
      function checkTree(node) {
        if (node.left != null) {
          var left = node.left;
          if (left.value > node.value) {
            check = false;
          } else {
            checkTree(left);
          }
        }
        if (node.right != null) {
          var right = node.right;
          if (right.value < node.value) {
            check = false;
          } else {
            checkTree(right);
          }
        }
      }
      checkTree(this.root);
      return check;
    }
  }
};
BinarySearchTree.prototype = {
  inOrder() {
    if (!this.root) {
      return null;
    }
    var result = new Array();
    function traverseInOrder(node) {
      node.left && traverseInOrder(node.left);
      result.push(node.value);
      node.right && traverseInOrder(node.right);
    }
    traverseInOrder(this.root);
    return result;
  }
};

Solution

function Node(value) {
  this.value = value;
  this.left = null;
  this.right = null;
}
function BinarySearchTree() {
  this.root = null;
  this.add = function(element) {
    let current = this.root;
    if (!current) {
      this.root = new Node(element);
      return;
    } else {
      const searchTree = function(current) {
        if (current.value > element) {
          if (current.left) {
            //si existe
            return searchTree(current.left);
          } else {
            current.left = new Node(element);
            return;
          }
        } else if (current.value < element) {
          if (current.right) {
            return searchTree(current.right);
          } else {
            current.right = new Node(element);
            return;
          }
        } else {
          return null;
        }
      };
      return searchTree(current);
    }
  };
}