Assignment 12

by Jeremy Boss

HTML

3*(x+5*y)
<br/>
Enter x:<input type="text" id="x" /><br>
Enter y:<input type="text" id="y" /><br>
<input type="button" value="Tree Me" onclick="makeTree()" /><br>
<p id="out1"></p>
<p id="out2"></p>

JavaScript

var string = "";
var Node = function(_cont){
  this.parent = null;
  this.left = null;
  this.right = null;
  this.content = _cont;
}
Node.prototype.addLeftNode = function (_cont){
	var n = new Node(_cont);
  n.parent = this;
  this.left = n;
  return n;
}
Node.prototype.addRightNode = function (_cont){
	var n = new Node(_cont);
  n.parent = this;
  this.right = n;
  return n;
}
function postOrd(n){
	if (n !== null){
  postOrd(n.left);
  postOrd(n.right);
  string = string + n.content;
  }
  return string;
}
function binTree(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();
}

Node.prototype.addNode = function(_cont) {

  var node = new Node(_cont);
  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.noc();
  var rightN = this.right.noc();

  if (leftN < rightN) {
    this.left.addNode(_cont);
  } else {
    this.right.addNode(_cont);
  }

  return this;
}

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

Node.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;
}

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