Assignment 12: Binary Trees

by MimiE

HTML

<p id="info">
This program calculates this expression using a binary tree and a stack:
3 * (x + 5 * y)
</p>

<label>Insert X: </label>
<input id="x" type=textbox ><br>
<br>
<label>Insert Y: </label>
<input id="y" type=textbox ><br><br>

<button onclick="createTree();">
Calculate
</button>
<br>
<div id=message>

</div>
<br>
<div id=output1>

</div>
<br>
<div id=output2>

</div>

CSS

#info {
  color:blue;
  font-size:20px;
}
button:focus {
  border: 1px solid blue;
  padding: 4px 4px;
}

JavaScript

// Call Variables
var str = "";
var TNode = function(_content){
  this.parent = null;
  this.left = null;
  this.right = null;
  this.content = _content;
}

TNode.prototype.addLeftNode = function (_content){
	var n = new TNode(_content);
  n.parent = this;
  this.left = n;
  return n;
}

TNode.prototype.addRightNode = function (_content){
	var n = new TNode(_content);
  n.parent = this;
  this.right = n;
  return n;
}

function postOrder(n){
	if (n !== null){
  postOrder(n.left);
  postOrder(n.right);
  str = str + n.content;
  }
  return str;
}

function Ctree(s){
	var operand = [];
	for (var i = 0, len = s.length; i < len; i++) {
	 if(!isNaN(s[i])){
   	operand.push(Number(s[i]));
   }
   else {
   	var operator = s[i];
    var b = operand.pop();
    var a = operand.pop();
    if (operator === "+"){
    	operand.push(a + b);
    }
    else if (operator === "-"){
    	operand.push(a - b);
    }
    else if (operator === "*"){
    	operand.push(a * b);
    }
    else if (operator === "/"){
    	operand.push(a / b);
    }
   }
  }
  return operand.pop();
}

TNode.prototype.addNode = 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 (leftN < rightN) {
    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...