Skip to content

Commit

Permalink
Added search function
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonheecs committed May 2, 2018
1 parent a818776 commit 6f29865
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 4 deletions.
31 changes: 29 additions & 2 deletions src/binary-search-tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@ class Node {
}

/**
* @return {Boolean}
* @return {boolean}
*/
isLeaf () {
return !this.left && !this.right;
}
}

/**
* search()
* findMin()
* findMax()
* preOrder()
Expand Down Expand Up @@ -61,4 +60,32 @@ export default class BST {
searchTree(node, this.root);
}
}

/**
* @param {*} value
* @return {(Node | boolean)}
*/
search (value) {
if (this.root === null) {
return false;
}

let current = this.root;

while (current !== null) {
if (value === current.value) {
return current;
}

if (value < current.value) {
current = current.left;
}

if (value > current.value) {
current = current.right;
}
}

return false;
}
};
35 changes: 33 additions & 2 deletions test/binary-search-tree-test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

import {BST} from '../src/index.js';
import {generateRandomNumbers} from './helper.js';
import {generateRandomNumbers, getRandomIntInclusive} from './helper.js';

const expect = require('chai').expect;

Expand All @@ -27,7 +27,7 @@ function checkIfTreeIsBST (tree) {
return false;
};

return checkSubtree(tree.root);
return checkSubtree(tree.root || tree);
}

describe('Test BST', function () {
Expand Down Expand Up @@ -56,4 +56,35 @@ describe('Test BST', function () {

expect(checkIfTreeIsBST(tree)).to.be.true;
});

it('test searching tree', function () {
let tree = new BST();

let randomData = generateRandomNumbers(50, 1, 9999);
randomData.forEach((value) => {
tree.add(value);
});

let randomIndex = getRandomIntInclusive(0, randomData.length - 1);
let searchResult = tree.search(randomData[randomIndex]);

expect(searchResult.value).to.equal(randomData[randomIndex]);
expect(checkIfTreeIsBST(searchResult)).to.be.true;
});

it('test searching for non-existent value', function () {
let tree = new BST();

let data = [1, 2, 3, 4, 5];
data.forEach((value) => {
tree.add(value);
});

expect(tree.search(10)).to.be.false;
});

it('test searching empty tree', function () {
let tree = new BST();
expect(tree.search(10)).to.be.false;
});
});

0 comments on commit 6f29865

Please sign in to comment.