COP3530 Assignment 12 - Binary Trees

by joseph_kanawall2400

HTML

3 * (X + 5 * Y)<br/>
X:<input type="number" id="xNum"/><br/>
Y:<input type="number" id="yNum"/><br/>
<input type="button" value="New Tree" onclick="genBinTree();"/>
<div id="output"/>

JavaScript

// Classes
function Node(value)
{
	this.content = value;
	this.parent = null;
	this.left = null;
	this.right = null;
	
	// Left Most Traversal
	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 count = 1;
		
		if(this.left != null)
		{
			count += this.left.nodeCount();
		}
		
		if(this.right != null)
		{
			count += this.right.nodeCount();
		}
		
		return count;
	}
	
	this.toString = function()
	{
		var string = "(";
		
		if(this.left != null)
		{
			string += this.left.content;
		}
		
		string += " " + this.content + " ";
		
		if(this.right != null)
		{
			if(this.right.nodeCount() > 1)
			{
				string += this.right.toString();
			}
			else
			{
				string += this.right.content;
			}
		}
		
		return string + ")";
	}
}

function BinTree()
{
	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 genBinTree()
{
	var x = document.getElementById("xNum");
	var y = document.getElementById("yNum");
	
	if(x.value == "" || y.value == "")
	{
		alert("Please enter a value in for X and Y.");
	}
	else
	{
		var bt = new BinTree();
		bt.add("*");
		bt.add("3");
		bt.add("+");
		bt.add(x.value);
		bt.add("*");
		bt.add("5");
		bt.add(y.value);

		var bts = bt.toString();

		document.getElementById("output").innerHTML += bts + " = " + eval(bts) + "<br/>";
		
		x.value = "";
		y.value = "";
	}
}