Binary Trees
by arosado417
HTML
<h1>
Assignment 12 – Binary Trees
</h1>
Enter a value for X.<br>
<input type="text" id="x_val"><br>
Enter a value for Y.<br>
<input type="text" id="y_val" ><br><br>
<input type="submit" onclick="calc()" />
<h3>
<p id="output">
</p>
</h3>
JavaScript
function calc()
{
//place to display the output
var d = document.getElementById("output");
var x = parseInt(document.getElementById("x_val").value);
var y = parseInt(document.getElementById("y_val").value);
if(isNaN(x) || isNaN(y)){
alert("Error: Please enter a number for x and y.");
return;
}
//create the leaves
var l3 = new leaf(3);
var lx = new leaf("x");
var l5 = new leaf(5);
var ly = new leaf("y");
//parent nodes
var first = new node("*", l5, ly);//5 * 1
var second = new node("+", lx, first);//1+5*1
var third = new node("*", l3,second);//3(1+5*1)
//evaluate the tree
var values = {};
values.x = x;
values.y= y;
var answer = third.traverse(values);
console.log(third.traverse(values));
//show the results
d.innerHTML = "X = " + x + ", Y = " + y + ", Output = " + answer;
}
//leaf node(for operands)
function leaf(value)
{
this.value = value;
}
//parent nodes for operators
function node(_content, left, right)
{
this.content= _content;
this.left = left;
this.right = right;
}
//traverse the tree
leaf.prototype.traverse = function(values)
{
if(isNaN(this.value))
{
return values[this.value];
}
return this.value;
}
node.prototype.traverse = function(values)
{
//get the values of the left then the right "children"
var left = this.left.traverse(values);
var right = this.right.traverse(values);
//do calculations according to the operator
var content = this.content;
if(content == "*")
{
return left * right;
}
if(content == "+")
{
return left + right;
}
return 0;
}
/*
Assignment 12 – Binary Trees
Objective
Demonstrate the ability to program more complex data structures
Supports learning outcome 1 and 3
1. Describe both complex and simple data structures.
3. Implement data structures and algorithms in computer code.
Introduction
Tree (of all sorts) are used throughout programming. You should become familiar with the types of trees and you will do a little bit of the use of trees. Trees are covered in Topic – Tree Data...