🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of chandrakishor

chandrakishor's solution

to Binary Search Tree in the JavaScript Track

Published at Mar 11 2021 · 0 comments
Instructions
Test suite
Solution

Insert and search for numbers in a binary tree.

When we need to represent sorted data, an array does not make a good data structure.

Say we have the array [1, 3, 4, 5], and we add 2 to it so it becomes [1, 3, 4, 5, 2] now we must sort the entire array again! We can improve on this by realizing that we only need to make space for the new item [1, nil, 3, 4, 5], and then adding the item in the space we added. But this still requires us to shift many elements down by one.

Binary Search Trees, however, can operate on sorted data much more efficiently.

A binary search tree consists of a series of connected nodes. Each node contains a piece of data (e.g. the number 3), a variable named left, and a variable named right. The left and right variables point at nil, or other nodes. Since these other nodes in turn have other nodes beneath them, we say that the left and right variables are pointing at subtrees. All data in the left subtree is less than or equal to the current node's data, and all data in the right subtree is greater than the current node's data.

For example, if we had a node containing the data 4, and we added the data 2, our tree would look like this:

  4
 /
2

If we then added 6, it would look like this:

  4
 / \
2   6

If we then added 3, it would look like this

   4
 /   \
2     6
 \
  3

And if we then added 1, 5, and 7, it would look like this

      4
    /   \
   /     \
  2       6
 / \     / \
1   3   5   7

Setup

Go through the setup instructions for Javascript to install the necessary dependencies:

https://exercism.io/tracks/javascript/installation

Requirements

Please cd into exercise directory before running all below commands.

Install assignment dependencies:

$ npm install

Making the test suite pass

Execute the tests with:

$ npm test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xtest to test.

Submitting Solutions

Once you have a solution ready, you can submit it using:

exercism submit binary-search-tree.js

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Exercise Source Credits

Josh Cheek https://twitter.com/josh_cheek

binary-search-tree.spec.js

import { BinarySearchTree } from './binary-search-tree';

function recordAllData(bst) {
  const out = [];

  bst.each((data) => out.push(data));

  return out;
}

describe('BinarySearchTree', () => {
  test('data is retained', () => {
    expect(new BinarySearchTree(4).data).toEqual(4);
  });

  describe('insert data at proper node', () => {
    xtest('smaller number at left node', () => {
      const four = new BinarySearchTree(4);
      four.insert(2);

      expect(four.data).toEqual(4);
      expect(four.left.data).toEqual(2);
    });

    xtest('same number at left node"', () => {
      const four = new BinarySearchTree(4);
      four.insert(4);

      expect(four.data).toEqual(4);
      expect(four.left.data).toEqual(4);
    });

    xtest('greater number at right node', () => {
      const four = new BinarySearchTree(4);
      four.insert(5);

      expect(four.data).toEqual(4);
      expect(four.right.data).toEqual(5);
    });
  });

  xtest('can create complex tree', () => {
    const four = new BinarySearchTree(4);
    four.insert(2);
    four.insert(6);
    four.insert(1);
    four.insert(3);
    four.insert(5);
    four.insert(7);

    expect(four.data).toEqual(4);
    expect(four.left.data).toEqual(2);
    expect(four.left.left.data).toEqual(1);
    expect(four.left.right.data).toEqual(3);
    expect(four.right.data).toEqual(6);
    expect(four.right.left.data).toEqual(5);
    expect(four.right.right.data).toEqual(7);
  });

  describe('can sort data', () => {
    xtest('can sort single number', () => {
      expect(recordAllData(new BinarySearchTree(2))).toEqual([2]);
    });

    xtest('can sort if second number is smaller than first', () => {
      const four = new BinarySearchTree(2);
      four.insert(1);

      expect(recordAllData(four)).toEqual([1, 2]);
    });

    xtest('can sort if second number is same as first', () => {
      const four = new BinarySearchTree(2);
      four.insert(2);

      expect(recordAllData(four)).toEqual([2, 2]);
    });

    xtest('can sort if second number is greater than first', () => {
      const four = new BinarySearchTree(2);
      four.insert(3);

      expect(recordAllData(four)).toEqual([2, 3]);
    });

    xtest('can sort complex tree', () => {
      const four = new BinarySearchTree(2);
      four.insert(1);
      four.insert(3);
      four.insert(6);
      four.insert(7);
      four.insert(5);

      expect(recordAllData(four)).toEqual([1, 2, 3, 5, 6, 7]);
    });
  });
});
class BinarySearchTreeNode {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

export class BinarySearchTree {
  constructor(data) {
    this.root = new BinarySearchTreeNode(data);
  }

  get data() {
    return this.root.data;
  }
  get right() {
    return this.root.right;
  }

  get left() {
    return this.root.left;
  }

  insert(data) {
    this.root = this._insert(this.root, data);
  }

  _insert(node, data) {
    if (node === null)  return new BinarySearchTreeNode(data);

    const cmp = data - node.data;
    if (cmp > 0)        node.right = this._insert(node.right, data);
    else if (cmp <= 0)  node.left = this._insert(node.left, data);
    
    return node;
  }

  each(callback) {
    this._inorder(this.root, callback);
  }

  _inorder(node, callback) {
    if (node === null)  return;

    this._inorder(node.left, callback);
    callback(node.data);
    this._inorder(node.right, callback);
  }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

chandrakishor's Reflection

All the APIs for this challenge were not mentioned explicitly. I had to examine the tests to find all of the methods that this class is supposed to have.

I don't know whether it was intentional or not but I think it was a good learning experience for me as I don't have much experience working with tests(either writing or reading them).

Any constructive comments are welcome!