Assignment 12 - Binary Trees

by aren_anderson

HTML

<h1>
Binary Trees
</h1>

<h3>
Equation: 3*(x+5y)
</h3>

<h4>
Enter x value: <input type="textbox" id="tbX"/>
</h4>
<h4>
Enter y value: <input type="textbox" id="tbY"/>
</h4>

<input type="button" id="btnCreate"  value="Create Tree" onclick="createTree();"/>

<br/><br/>
<div id="output">
</div>

JavaScript

debugger;

//create node for binary tree
var tNode = function(content){
	this.parent = null;
  this.left = null;
  this.right = null;
  this.content = content;
}

//method to add node to binary tree
tNode.prototype.add = function(content){
	var node = new tNode(content);
  if(this.left == null){
  	node.parent = this;
    this.left = node;
    return this;
  }
  if(this.right == null){
  	node.parent = this;
    this.right = node;
    return this;
  }
  var leftN = this.left.numberOfChildren();
  var rightN = this.right.numberOfChildren();
  
  if(this.left.content == "+" || this.left.content == "*" || this.left.content == "-"){
  	this.left.add(content);
  }else if(this.right.content == "+" || this.right.content == "*" || this.right.content == "-"){
  	this.right.add(content);
  }
  return this;
}

tNode.prototype.numberOfChildren = function(){
	var n = 0;
  if(this.left != null){
  	n = 1 + this.left.numberOfChildren();
  }
  if(this.right != null){
  	n = n + 1 + this.right.numberOfChildren();
  }
  return n;
}

//function to create tree
var BinaryTree = function(){
	this.top = null;
  this.bottom = null;
  this.addNode = function(content){
  	if(this.top == null){
    	var node = new tNode(content);
      this.top = node;
      return this;
    }
    this.top.add(content);
    return this.bottom;
  }
 this.getBottom = function(){
 	var current = this.top;
  while(current.left != null){
  	current = current.left;
  }
  this.bottom = current;
  return this.bottom;
  }
	this.traverse = function(root){
  	if(root === null){
    	return this.top.content;
    }
    if(root == this.bottom){
    	this.traverse(root.parent.right.right);
    }
    if(root.content == "*" || root.content == "/" || root.content == "+" || root.content == "-"){
    	this.checkOperator(root);
    }
    else{
    	if(root.left != null){
      	this.traverse(root.left);
      }
      if(root.right != null){
      	this.traverse(root.right);
      }
    }
  }
  
  //check nodes for operators...