-
Notifications
You must be signed in to change notification settings - Fork 411
Binary Search Tree (BST)
Felipe Ribeiro edited this page Feb 18, 2014
·
13 revisions
A binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- The left and right subtree each must also be a binary search tree.
- There must be no duplicate nodes.
Source: Wikipedia
Code: https://github.com/felipernb/algorithms.js/blob/master/data_structures/bst.js
Tests: https://github.com/felipernb/algorithms.js/blob/master/test/data_structures/bst.js
var bst = new BST();
bst.insert(4);
bst.insert(8);
bst.insert(10);
bst.insert(2);
bst.insert(1);
bst.insert(3);
bst.insert(0);
bst.insert(5);
bst.insert(100);
/**
* The, you're gonna have something like:
*
* 4
* 2 8
* 1 3 5 10
* 0 2.5 100
*/
Points to the Node that is the root of the tree, for the tree above, bst.root
will be:
{
value: 4,
parent: null,
left: { value: 2, ...},
right: { value: 8, ...}
}
Returns if the tree contains the passed element (in O(lg n))
bst.contains(4); //true
bst.contains(3); //true
bst.contains(0); //true
bst.contains(22); //false
bst.contains(-1); //false
Removes an element from the tree and reorganizes it (in (O(lg n))
/**
* 4
* 2 8
* 1 3 5 10
* 0 2.5 100
*/
bst.remove(0);
/**
* 4
* 2 8
* 1 3 5 10
* 2.5 100
*/
bst.remove(4);
/**
* 5
* 2 8
* 1 3 10
* 2.5 100
*/
bst.remove(2)
/**
* 5
* 2.5 8
* 1 3 10
* 100
*/
Returns the size of the tree