Saturday, September 6, 2014

Binary Tree using HTML5 Canvas and JavaScript

Hi Guys -

I was just playing around with HTML5 Canvas and thought it will be fun to create a binary tree implementation using JavaScript.

I tried this a few years ago with Java and applets. Well, yeah u guessed it, it was a PITA.

With JavaScript and Canvas, it was a smooth ride.

The code below is only for the purpose of demo. Some nodes might overlap if the tree has a lot
of nodes.

Tested on Google Chrome

1 - Create a file index.html and add the below code to it.
      It contains an
      a - Input box where the user will enter the number to be added
      b - A button to add entered number
      c - A canvas element
      d - A script tag


     
2 - Next we will add a node object. Node, as the name suggests, represent a node in the tree
     Add the below code in the script tag of the index.html

   

3 - Next we will add code to draw a line from parent to child. Add the below code to the script tag    
   


4 - Next we add the core logic of a binary tree. To understand that logic, you should know how
     a binary tree works. Add the blow code the script tag

   

5 - Now we  need to create a binary tree object to which we can add node
 
     Add the below code to the script tag

     var btree = new BTree();

6 - Ok. We are almost done. We just need to wire the input box and add to tree button
     Add the below code to the script tag