btree
A rebalancing binary tree for JS
To install / use:
npm install btree-js
Basic Usage
var BinaryTree = ;var Tree = BinaryTreeTree;var Node = BinaryTreeNode; var tree = ;tree; // becomes tree's roottree; // tree.root.right.key: 15
Options
key
The binary tree defaults to key property unless a key is explicitly passed in.
var tree = key: 'id' ;tree;console; // 1
unique
The binary tree defaults to allowing multiple identical keys. If unique: true
is passed in as an option, it will throw an error when inserting a duplicate key.
var tree = unique: true ;tree; // throws duplicate key violation
API
isEmpty
Returns whether or not the tree has nodes in it.
var tree = ;console; // true tree
delete
Allows you to pass in either a node or a key to delete that node from the tree. If the tree becomes unbalanced as a result, it will rebalance itself.
tree;tree; 5 3 10 8 tree;tree; 8 5 10
min
Returns the minimum key in the tree. If a node is provided, it will find the minimum key in that subtree.
tree;console; // 25 tree;console; // 40
max
Returns the maximum key in the tree. If a node is provided, it will find the maximum key in that subtree.
tree;console; // 180 tree;console; // 90
search
Returns a node with the given key, if found. Otherwise, returns null
.
tree;tree; var node = tree;console; // plopconsole; // 10
findPaths
Returns a list of paths from the root to the leaf (array of array of nodes).
tree;var paths = tree;paths; // 2 1// 2 3
height
Returns the height of the tree. With n
nodes, the height of the
tree will be approximately log(n)
.
var tree = ;tree;treeheight; // 3
invert
Inverts the tree by taking all the node pointers and flipping them.
tree;tree; 50 25 75 60 90 tree;tree; 90 25 50 60 75
To print a text-view of the tree,
tree; 7 3 13 1 5 9 17 2 4 6 8 11 15 18 14 19
inOrderTraversal
An iterator that returns the nodes via:
- Return node from left tree (recursive)
- Return self
- Return node from right tree (recursive)
tree;
preOrderTraversal
An iterator that returns the nodes via:
- Return self
- Return node from left tree (recursive)
- Return node from right tree (recursive)
tree;
postOrderTraversal
An iterator that returns the nodes via:
- Return node from left tree (recursive)
- Return node from right tree (recursive)
- Return self
tree;
Written by JT Bowler, 2016.