<!-- Heading 1 -->
<h2> Austin Millett </h2>
<!-- Heading 2 -->
<h3> Assignment 12 - Binary Trees </h3>
<!-- Textbox 1 -->
Please enter a X value:
<input type = "textbox" id = "xValue" /> <br> <br>
<!-- Textbox 2 -->
Please enter a Y value:
<input type = "textbox" id = "yValue" /> <br> <br>
<!-- Button for "Submit" -->
<input type = "button" id = "submit" value = "Submit" onclick = "XandY();" /> <br> <br>
<!-- Div for output -->
<div id = "output"> </div>
this.XandY = function() {
var x = document.getElementById("xValue").value.trim();
var y = document.getElementById("yValue").value.trim();
x = parseFloat(x);
y = parseFloat(y);
// If invalid Input print "Invalid Input"
if (isNaN(x) || isNaN(y)) {
output.innerHTML = "Invalid Input";
return;
}
// Binary tree
var leaf3 = new leaf(3);
var leafx = new leaf("x");
var leaf5 = new leaf(5);
var leafy = new leaf("y");
var mult = new node("*", leaf5, leafy);
var add = new node("+", leafx, mult);
var mult2 = new node("*", leaf3, add);
// Assigning value of x and y to "x" and "y"
var valueOf = {};
valueOf["x"] = x;
valueOf["y"] = y;
var result = mult2.traverse(valueOf);
// Output
output.innerHTML = "X = " + x + ", Y = " + y + ", Output = " + result;
};
function leaf(valueOf) {
this.value = valueOf;
}
function node(key, left, right) {
this.key = key;
this.left = left;
this.right = right;
}
leaf.prototype.traverse = function(valueOf) {
if (isNaN(this.value)) {
return valueOf[this.value];
}
return this.value;
};
node.prototype.traverse = function(valueOf) {
var left = this.left.traverse(valueOf);
var right = this.right.traverse(valueOf);
var key = this.key;
// "Addition, Subtraction, Multiplication, Division"
if (key == '+') {
return left + right;
}
if (key == "-") {
return left - right;
}
if (key == '*') {
return left * right;
}
if (key == '/') {
return left / right;
}
return 0;
};
// Output
var output = document.getElementById("output");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.