JSFiddle - React, Tailwind, and code Playground

by Ron Eaglin

HTML

To use this code - you will need to Fork this version to create your own. You will also need to change the code so that numbers, rather than strings are added and you use the equation provided to you in the assignment.<br/><br/>
Equation used (keep this): <b>X + Y</b><br/><br/>
 
  Enter x and y and hit compute to calculate traversal of the tree<br/>
  <input type="text" id="x" placeholder="Enter x">
  <input type="text" id="y" placeholder="Enter y">
  <button onclick="compute()">Compute</button>
  <br/>
  <div id="output">
  
  </div>

JavaScript

function compute() {
      // Get the values of x and y from the input fields
      let x = document.getElementById("x").value;
      let y = document.getElementById("y").value;

      // You can perform calculations or other operations with x and y here
      let result = createAndTraverseTree(x,y); // Example: Add x and y

      // Display the result (or perform other actions)
      document.getElementById("output").innerHTML = "The result is " + result
    } 
    
function createAndTraverseTree(x,y){
// Create the Tree - you need to use the actual equation given
// in the discussions to create your tree. So your code will be 
// different than the code given here. 

	var leaf1 = new leaf(x); // create a leaf with value of 1
	var leaf2 = new leaf(y); // create a leaf with value of 2
	var root= new node('+', leaf1, leaf2); // the root node will be +
  
	v = []; // Holds current value
	var result = root.traverse(v); //
	return result;
}
    
function leaf(value) {
  this.value = value
}

function node(key, left, right) {
  this.key = key
  this.left = left
  this.right = right
}

leaf.prototype.traverse = function(values) {
  if (isNaN(this.value)) {
    return values[this.value]
  }
  return this.value
}

node.prototype.traverse = function(values) {
  var left = this.left.traverse(values)
  var right = this.right.traverse(values)
  var key = this.key
  if (key == '+') {
    return left + right
  }
  if (key == '-') {
    return left - right
  }
  if (key == '*') {
    return left * right
  }
  if (key == '/') {
    return left / right
  }
  return 0
}