JSFiddle - React, Tailwind, and code Playground

by puuga

HTML

<body>
    <h1>Javascript Objects</h1>
    <div><button onclick="goPressed()">Go</button></div>
    <h2>Output</h2>
    <div id="output1"></div>
    <div id="output2"></div>
</body>

CSS

body {
    margin: 10px;
    font-family: Helvetica;
}
h1 {
    font-size: 140%;
    margin-bottom: 20px;
}
h2 {
    font-size: 110%;
    margin: 10px 0;
}

JavaScript

//test tree

function goPressed() {

    // Input
    var rootNode = {
        value: "+"
    };
    rootNode.left = {
        value: "1"
    };
    rootNode.right = {
        value: "/"
    };
    rootNode.right.left = {
        value: "2"
    };
    rootNode.right.right = {
        value: "+"
    };
    rootNode.right.right.left = {
        value: "3"
    };
    rootNode.right.right.right = {
        value: "4"
    };


    //alert(rootNode.left.right.value);
    // pass list of object to function then return object which is the most expensive
    var output1 = printBinaryTree(rootNode);
    var output2 = travelTree(rootNode) + "=" + calculate(rootNode);

    // Output
    $('#output1').html(output1);
    $('#output2').html(output2);

}

function printBinaryTree(node) {
    output = "";
    if (node.left != undefined) {
        output += printBinaryTree(node.left);
    } else if (node.left == undefined) {
        return node.value;
    }
    output += node.value;
    if (node.right != undefined) {
        output += printBinaryTree(node.right);
    } else if (node.right == undefined) {
        return node.value;
    }
    return output;
}

function travelTree(node) {
    return node.left == undefined && node.right == undefined ? node.value : travelTree(node.left) + node.value + travelTree(node.right);
}

function calculate(node) {
    //base case
    if (node.left == undefined) {
        return parseFloat(node.value);
    }
    if (node.value == "+") {
        return calculate(node.left) + calculate(node.right);
    }
    if (node.value == "-") {
        return calculate(node.left) - calculate(node.right);
    }
    if (node.value == "*") {
        return calculate(node.left) * calculate(node.right);
    }
    if (node.value == "/") {
        return calculate(node.left) / calculate(node.right);
    }
    //return calculate(node.left) + node.value + calculate(node.right);
}