A12 Binary Tree
by scotp71
HTML
<br/>
<input type="textbox" id="xval" value="Enter X" />
<input type="textbox" id="yval" value="Enter Y" />
<input type="button" value="Submit" onClick="createTree()"/>
<br/>
<p id="output"></p>
JavaScript
var TNode = function(_content) {
this.parent = null;
this.left = null;
this.right = null;
this.content = _content;
}
TNode.prototype.addNode = function(_content) {
var _node = new TNode(_content);
// if no left - add to left
if (this.left == null) {
_node.parent = this;
this.left = _node;
return this;
}
if (this.right == null) {
_node.parent = this;
this.right = _node;
return this;
}
if (_content=="*" || _content=="/" || _content=="+" || _content=="-") {
this.left.addNode(_content);
}
else {
this.left.addNode(_content);
}
return this;
}
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 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;
}
}
var array = [];
BinaryTree.prototype.print = function() {
if (this.top != null) return this.top.print();
}
//function to compute the answer of the formula in the tree
BinaryTree.prototype.compute = function() {
if (this.top !=null){
var node = new TNode();
node = this.top;
var bottomNode = findBottom(node);
var result = bottomNode.content;
var op = bottomNode.parent;
var otherVar = op.right;
var a, b, c, answer;
//loop to transverse back up the tree, computing the equation on the way
while(op!=null){
a = result;
b...