Binary Expression(80%working)
Assignment 12
by Alan Harris
HTML
<p id="info">
This program calculates this expression using a binary tree and a stack:
3 * (x + 5 * y)
</p>
<label>Insert X: </label>
<input id="xVal" type=textbox ><br>
<br>
<label>Insert Y: </label>
<input id="yVal" type=textbox ><br><br>
<button onclick="Insert();">
Calculate
</button>
<div id="print">
</div>
CSS
#info {
color:black;
font-size:20px;
}
button:focus {
border: 1px solid black;
padding: 4px 4px;
}
button {
background-color: grey;
border: 1px solid black;
color: white;
padding: 4px 8px;
text-decoration: none;
margin: 4px 2px;
}
button:hover {
background-color:black;
}
JavaScript
var p = "";
var Node = function(element) { // Node for stack
this.content = element;
this.next = null;
this.last = null;
return this;
}
var TrNode = function(element) { //Node for binary tree
this.root = null;
this.leftn = null;
this.rightn = null;
this.content = element;
}
TrNode.prototype.Nodeadd = function(element) {
var n = new TrNode(element);
if (this.leftn == null) {
n.root = this;
this.leftn = n;
return this;
}
if (this.rightn == null) {
n.root = this;
this.rightn = n;
return this;
}
var leftNod = this.leftn.numberofChildren();
var rightNod = this.rightn.numberofChildren();
if (leftNod < rightNod) {
this.leftn.Nodeadd(element);
}
else {
this.rightn.Nodeadd(element);
}
return this;
}
TrNode.prototype.numberofChildren = function() {
var a = 0;
if (this.leftn != null){
a = 1 + this.leftn.numberofChildren();
}
if (this.rightn != null) {
a = a + 1 + this.rightn.numberofChildren();
}
return a;
}
var bTree = function() {
this.r = null;
this.aNode = function(element) {
if (this.r == null) {
var nod = new TrNode(element);
this.r = nod;
return this;
}
this.r.Nodeadd(element);
return this;
}
}
var Stack = function() {
this.head = null;
this.top = null;
this.push = function(element) {
if (this.head == null) {
this.head = new Node(element);
this.top = this.head;
return this;
}
var node_Input = new Node(element);
node_Input.last = this.top;
this.top.next = node_Input;
this.top = node_Input;
return this;
}
this.pop = function() {
if (this.head == null) {
alert("Empty Stack");
return null;
}
if (this.head == this.top) {
this.head = null;
return this.top.content;
}
var n = this.top.content;
this.top = this.top.last;
this.top.next = null;
return n;
}
this.print = function() {
var s = "";
var node = this.head;
while (node != null) {
s += node.content + "...