JSFiddle - React, Tailwind, and code Playground

by Jeff Santos

HTML

3 * (x + 5 * y)<br/> 
<br/> 
 
Please Enter Values for x and y.
<br/> 
<br/>
x:
<input type="number" id="xVal" />
<br/> y:
<input type="number" id="yVal" />
<br/><br/>
<input type="button" value="New Tree" onclick="binTree();" />
<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 c = 1;

    if (this.left != null) {
      c += this.left.nodeCount();
    }

    if (this.right != null) {
      c += 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 tree() {
  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 binTree() {
  var x = document.getElementById("xVal");
  var y = document.getElementById("yVal");

  if (x.value == "" || y.value == "") {
    alert("Please enter a value in for x and y!");
  } else {
    var t = new tree();
    t.add("*");
    t.add("3");
    t.add("+");
    t.add(x.value);
    t.add("*");
    t.add("5");
    t.add(y.value);

    var bts = t.toString();

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

    x.value = "";
    y.value = "";
  }
}