Javascript data structures - the binary tree
Written by Mike James   
Thursday, 18 September 2014
Article Index
Javascript data structures - the binary tree
Tree relative
Listing

 The full listing


function BinaryTree(){
this.Nodes = new Array();
this.level = 0;
this.node = 0;

this.setNode = function(value,level,node){
  if (level === undefined) {
  this.Nodes[this.btSMF(this.level, this.node)] = value;
  }else {
   this.Nodes[this.btSMF(level,node)] = value;
  }
}

this.getNode = function(level, node){
  if (level === undefined) {
   return this.Nodes[this.btSMF(this.level,this.node)];
  }else {
   return this.Nodes[this.btSMF(level,node)];
  }
}

this.root = function(value){
  this.level = 0;
  this.node = 0;
  if (value !== undefined) {
   this.Nodes[this.btSMF(this.level,this.node)] = value;
  }
  return this.Nodes[this.btSMF(this.level,this.node)];
}

this.leftChild = function(value){
  this.level++;
  this.node = this.node * 2;
  if (value !== undefined) {
   this.Nodes[this.btSMF(this.level,this.node)] = value;
  }
  return this.Nodes[this.btSMF(this.level,this.node)];
}

this.rightChild = function(value){
  this.level++;
  this.node = this.node * 2 + 1;
  if (value !== undefined) {
this.Nodes[this.btSMF(this.level, this.node)] = value;
  }
  return this.Nodes[this.btSMF(this.level, this.node)];
}

this.parent = function(value){
  this.level--;
  this.node = this.node >> 1;
  if (value !== undefined) {
   this.Nodes[this.btSMF(this.level, this.node)] = value;
  }
  return this.Nodes[this.btSMF(this.level,this.node)];
}

this.btSMF = function(level, node){
  return node + (1 << level) - 1;
 }

 

If you would like the code for this project then register and click on CodeBin.

 

jemsicon

JavaScript Data Structures

 

 

 

 

Related Articles

Data structures - Trees       

The Lost Art Of The Storage Mapping Function       

Recursion  

    

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

 

Banner
 


Just JavaScript - Object Construction

Object creation is fundamental to all object-oriented languages, but in JavaScript is is left to the programmer to work out how best to do it and often the practice that you encounter isn't the best b [ ... ]



Just JavaScript - The Object Expression

As in most programming languages the expression is an important part of JavaScript, but it isn't quite the same. This is where the idea that JavaScript has some weird type conversions arises. But Java [ ... ]


Other Articles

 

blog comments powered by Disqus

 



Last Updated ( Thursday, 18 September 2014 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.