Site Search:

How to Build a Binary Search Tree with Javascript


A binary search tree is a tree structure with the following constraints:

  1. parent node value above the left child node value
  2. parent node value below the right child node value
We can construct a binary search tree with javascript step by step.

step 1. find an representation of tree with html.
Fancy tree like graphs can be build with vis.js or d3.js, or Treant.js,
here I choose a simple presentation like the following 2 versions:
version 1:
binary search tree simple presentation
the view is generated with nested <ul> <li> and css, source code is here
version 2:
Treant.js tree fancy presentation
the view is generated with the library code
var my_chart = new Treant( simple_chart_config );

step 2. build the javascript binary search tree interface implementations.
A tree should have a constructor and common methods such as insert(key), delete(key), size(), contains(key), min(), deleteMin() etc.
Fancy implementation can have rank(), floor(key), roof(key) etc.

Here is basic implementation with javascript.
Source code of this javascript code can be found here.

step 3. traversal the tree nodes and build the corresponding html presentation, so that we can visualize a tree data structure.
We can build the nested <ul> <li> html code by recursively visit all the nodes of the tree.
Here is the UI for a tree
Here is the javascript code of the UI


step 4. allow user to interactively add/remove node and update the view accordingly.



Notice the tricky part is you need to convert the input field's value to number with parseInt(), otherwise you are comparing characters instead of number

The source code is here