Binary Search Tree (in Javascript)
Usage
Install from NPM:
npm i bst-js
const Node = ;// create a tree with the root node value of 5const tree = 5;
The above will assume that the value of each node is a number. If you would like to store other forms of data, you will need to use your own comparator so that the tree can properly be sorted:
const tree = "f" { if x < y return -1; if x > y return 1; return 0;}; tree;// f// / \// b p// / \// l z
Methods
insert
Inserts a node with the given value.
const tree = 9;// 9// /// 4
or insert many values at once.
const tree = 5;const newValues = 10 1 8 7;tree; // or tree.insert(10, 1, 8, 7)// 5// / \// 1 10// /// 8// /// 7
delete
Deletes a node with the given value.
const tree = 5;// 5// / \// 1 10// /// 8// /// 7tree;// 5// / \// 1 8// /// 7
or insert many values at once.
const tree = 5;const oldValues = 10 1;tree; // or tree.delete(10, 1)// 5// / \// 1 8// /// 7
isBalanced
Returns true if the height of the left and right subtrees have a difference of 1 or less.
const tree = 5;tree; tree;// true
height
Returns the height of a given tree or subtree.
const tree = 5; treeheight;// 3
depth
const tree = 5; tree;// 2
size
Returns the total number of nodes in a tree or subtree.
const tree = 5; treesize;// 5
contains
Returns true if a tree/subtree contains the passed value.
const tree = 5; tree;// true
depthFirst
Will execute a callback with each node's context bound to this
over a depthFirst PREORDER
traversal (by default). It also supports INORDER
and POSTORDER
traversals.
const tree = 5; tree;// 5, 10, 1, 8, 7 tree;// 1, 5, 7, 8, 10
breadthFirst
Will execute a callback with each node's context bound to this
over a breadthFirst traversal.
const tree = 5;// 5// / \// 1 10// / /// 0 8// /// 7 tree;// 5, 1, 10, 0, 8, 7