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 - Life Without Type - Constructor And InstanceOf

JavaScript is a subtle and sophisticated language that deserves to be treated in its own right and not as a poor copy of other object-oriented language. In this chapter (Chapter 8) Ian Elliot explores [ ... ]



Just JavaScript - Type And Non-Type

What is the fuss about strong typing really all about? JavaScript doesn't make much use of type so what is it missing? What is more difficult to do in JavaScript than in a typed language? Are there th [ ... ]


Other Articles

 

blog comments powered by Disqus

 



Last Updated ( Thursday, 18 September 2014 )
 
 

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