Assignment 12

Binary Trees

by F Fornos

HTML

<h2>
Binary tree representation of the equation:
3(x + 5y)
</h2> Please enter the values for X:
<input type="text" id="x" size="2" /> Y:
<input type="text" id="y" size="2" />
<input type='button' value='Calculate' onclick='calculate();' />
<br/>
<br/>

<span id='output' />

JavaScript

window.calculate = function() {
  var output = document.getElementById('output');
  var x = document.getElementById('x').value.trim();
  var y = document.getElementById('y').value.trim();
  x = parseFloat(x);
  y = parseFloat(y);

  if (isNaN(x) || isNaN(y)) {
    output.innerHTML = "<h3>Invalid Input - Not an Integer</h3>";
    return;
  }

  var node3 = new branch(3);
  var nodeX = new branch("x");
  var node5 = new branch(5);
  var nodeY = new branch("y");
  var op1 = new node("*", node5, nodeY);
  var op2 = new node("+", nodeX, op1);
  var op3 = new node("*", node3, op2);
  var values = {};

  values["x"] = x;
  values["y"] = y;

  var ressult = op3.traverse(values);

  output.innerHTML = "X = " + x + ", Y = " + y + ", Output = " + ressult;
};

function branch(value) {
  this.value = value;
}

function node(op, left, right) {
  this.op = op;
  this.left = left;
  this.right = right;
}

branch.prototype.traverse = function(values) {
  if (isNaN(this.value)) {
    return values[this.value];
  }

  return this.value;
};

node.prototype.traverse = function(values) {
  var left = this.left.traverse(values);
  var right = this.right.traverse(values);
  var op = this.op;

  if (op == '+') {
    return left + right;
  }

  if (op == "-") {
    return left - right;
  }

  if (op == '*') {
    return left * right;
  }

  if (op == '/') {
    return left / right;
  }

  return 0;

};