Binary Trees

Assignment 12

by Taylor Zimmerman

HTML

Equation: 3 * (x + 5 * y)
<br/>
<br/>
Please enter a numerical value for x and y:
<br/>
<br/>
x = <input type = "textbox" id = "xvalue" xvalue = "" />
y = <input type = "textbox" id = "yvalue" yvalue = "" />
<input type = "button" id = "button1" value = "Calculate result" onClick="Calculate()" />
<br/>
<p id="output1"></p>
<br/>
<p id="output2"></p>

JavaScript

var TNode = function(_content, _left, _right) {
    this.content = _content;
    this.left = _left;
    this.right = _right;
}

TNode.prototype.traverse = function() {
    var left = this.left.traverse();
    var right = this.right.traverse();
    switch (this.content) {
        case "+":
            return (left + right);
            break; 
        case "*":
            return (left * right);
            break;
    }
}

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 TLeaf = function(_content) {
    this.content = _content;
}

TLeaf.prototype.traverse = function() {
    return this.content;
}

TLeaf.prototype.print = function() {
    var s = "";
    return s;
}

Calculate = function() {
    clearDisplay();
    var x = parseFloat(document.getElementById("xvalue").value);
    var y = parseFloat(document.getElementById("yvalue").value);
    
    if (isNaN(x) || isNaN(y)) {
        document.getElementById("output1").innerHTML += "Error: x and y must both be numbers.";
        return;
    }

    var node3 = new TLeaf(3);
    var nodeX = new TLeaf(x);
    var node5 = new TLeaf(5);
    var nodeY = new TLeaf(y);

    // operator nodes
    var multInner = new TNode("*", node5, nodeY); // 5 * y
    var addition  = new TNode("+", nodeX, multInner); // x + 5 * y
    var multOuter = new TNode("*", node3, addition);  // 3 * (x + 5 * y)

    var result = multOuter.traverse();

    // display result
    document.getElementById("output1").innerHTML += "X = " + x + "<br/>" + "Y = " + y + "<br/>" + "Equation: 3 * (" + x + " + 5 * "...