Assignment 12 binary tree
by pat spag
HTML
Evaluate for [3*(x + 5*y)]
<br>
Input X:
<input type="text" id="x" value="" size='3'>
<br>
Input Y:
<input type="text" id="y" value="" size="3">
<br>
<input type="button" id="submit" value="submit" onclick="createTree()">
<br>
<div id="output">
</div>
<div id="output2">
</div>
JavaScript
//modified from example
var TNode = function(val,left,right) {
this.parent = null;
this.left = null;
this.right = null;
this.content = val;
this.addLeft = function (leftVal){
var n = new TNode(leftVal);
n.parent = this;
this.left = n;
return n;
}
this.addRight = function (rightVal){
var n = new TNode(rightVal);
n.parent = this;
this.right = n;
return n;
}
// used the same print functions from example
this.print = function() {
var s = this.printNode();
if (this.left != null) {
s += this.left.print();
}
if (this.right != null) {
s += this.right.print();
}
return s;
}
this.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 BinaryTree = function() {
this.top = null;
this.addNode = function(_content) {
// If no top node - add to top
if (this.top == null) {
var _node = new TNode(_content);
this.top = _node;
return this;
}
// otherwise let node select
this.top.addNode(_content);
return this;
}
this.print = function() {
if (this.top != null) return this.top.print();
}
}
function treeExpression(treeNode){
if (treeNode !== null){
treeExpression(treeNode.left);
treeExpression(treeNode.right);
str = str + treeNode.content;
}
return str;
}
function calculateTree(expression){
var numbers = [];
for (var i = 0; i < expression.length; i+=1) {
var expressionVal= expression[i];
if(!isNaN(expressionVal)){
numbers.push(parseInt(expressionVal));
} else {
var operandX = numbers.pop();
var operandY = numbers.pop();
if (expressionVal === "+"){
numbers.push(operandY + operandX);
}
else if (expressionVal === "-"){
numbers.push(operandY - operandX);
}
else if (expressionVal === "*"){
...