JSFiddle - React, Tailwind, and code Playground
by Jeff Santos
HTML
[3 * (x + 5 * y)]<br/>
<br/>
Please Enter Values for x and y.
<br/>
<br/>
x:
<input type="number" id="xVal" />
y:
<input type="number" id="yVal" />
<br/><br/>
<input type="button" value="New Tree" onclick="binTree();" />
<br/>
<div id="output" />
JavaScript
// Classes
function Node(value) {
this.content = value;
this.parent = null;
this.left = null;
this.right = null;
this.addNode = function(value) {
var _newNode = new Node(value);
if (this.left == null) {
_newNode.parent = this;
this.left = _newNode;
} else if (this.right == null) {
_newNode.parent = this;
this.right = _newNode;
} else {
this.right.addNode(value);
}
return this;
}
this.nodeCount = function() {
var c = 1;
if (this.left != null) {
c += this.left.nodeCount();
}
if (this.right != null) {
c += this.right.nodeCount();
}
return c;
}
this.toString = function() {
var s = "(";
if (this.left != null) {
s += this.left.content;
}
s += " " + this.content + " ";
if (this.right != null) {
if (this.right.nodeCount() > 1) {
s += this.right.toString();
} else {
s += this.right.content;
}
}
return s + ")";
}
}
function tree() {
this.top = null;
this.add = function(value) {
if (this.top == null) {
this.top = new Node(value);
} else {
this.top.addNode(value);
}
return this;
}
this.toString = function() {
if (this.top == null) {
return "";
} else {
return this.top.toString();
}
}
}
// Other Functions
function binTree() {
var x = document.getElementById("xVal");
var y = document.getElementById("yVal");
if (x.value == "" || y.value == "") {
alert("I must insist you enter a Numerical Value for x and y!");
} else {
var t = new tree();
t.add("*");
t.add("3");
t.add("+");
t.add(x.value);
t.add("*");
t.add("5");
t.add(y.value);
var bts = t.toString();
document.getElementById("output").innerHTML += bts + " = " + eval(bts) + "<br/>";
x.value = "";
y.value = "";
}
}