binary_tree

by davidjb95

HTML

input numbers for X and Y:
<br/>X:
<input type="textbox" id="varX" Value="1" />
<br/>Y:
<input type="textbox" id="varY" Value="1" />
<br/>
<input type="button" value="Create Tree" onclick="createTree()" />
<p id="output"></p>
Final Answer:<p id="outputAnswer"></p>

JavaScript

var TNode = function(_content) {
  this.parent = null;
  this.left = null;
  this.right = null;
  this.content = _content;
}

TNode.prototype.addNode = function(_content) {

  var _node = new TNode(_content);
  // if no left - add to left
  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 (leftN = 0) {
    this.left.addNode(_content);
  } else {
    this.right.addNode(_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;
}

TNode.prototype.print = function() {
  var s = this.printNode();
  if (this.left != null) {
    s += this.left.print();
  }
  if (this.right != null) {
    s += this.right.print();
  }
  return s;
}

TNode.prototype.printNode = function() {
  var s = "Node: " + this.content;
  if (this.left != null) {
    s += " Left: " + this.left.content;
  }

  if (this.right != null) {
    s = s + " Right: " + this.right.content;
  }
  s += "<br />";

  return s;
}


var BinaryTree = function() {
  this.top = null;

  this.addNode = function(_content) {
    // If no top node - add to top 
    if (this.top == null) {
      var _node = new TNode(_content);
      this.top = _node;
      return this;
    }
    // otherwise let node select
    this.top.addNode(_content);
    return this;
  }
  this.calculate = function() {
    var insertX = document.getElementById("varX").value;
  	var insertY = document.getElementById("varY").value;
    var calculating = this.top;
    var rightT = calculating.right.numberOfChildren();
    var rightN = calculating.right.numberOfChildren();
    while(rightN > 1){
    	//finds the bottom of...