Paul_was_taken
Paul_was_taken

Reputation: 51

Printing trees in javascript

I need to print my tree but I don't know how to do it. I guess I may use recursion. I wonder if there are any easier ways? Here is the code.

var tree = new Object();
string = "23*4+5-";
tree = MakeMeATree(string, string.length - 1);

function MakeMeATree(string, t)
{
    var tree = {};
    if (t == 0) return;
    tree.name = string.charAt(t);
    t--;
    if ( isOperand(string.charAt(t)))
    {
        tree.left = string.charAt(t);
        tree.right = string.charAt(t-1);
        t--;
        tree.left = MakeMeATree(string, t);
    }
    if ( isOperand(string.charAt(t-1)))
    {
        tree.left = string.charAt(t-1);
        tree.right = string.charAt(t);
        t--;
        tree.left = MakeMeATree(string, t);
    }
    else 
    {
        tree.left = string.charAt(t);
        tree.right = string.charAt(t-1);
        t--;
    }
    return tree;
}

Also I am not sure about returnings, I mean should I use return tree both times? or just in the end?

UPD: This function works I guess

PrintMeTree(tree);
    function PrintMeTree(tree)
    {
        while (tree.name != undefined && tree.left != undefined && tree.right != undefined)
        {
            WScript.Echo(tree.name + " " + tree.left + " " + tree.right);
            PrintMeTree(tree.left)
            PrintMeTree(tree.right)
            return;
        }
    } 

Upvotes: 0

Views: 162

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29936

This will make you a tree.

function isOperand(term) {
    return /[0-9]/.test(term);
}
function MakeMeATree(string) {
    var p = string.length - 1;
    function consumeTree() {
        var op = string.charAt(p--);
        if (isOperand(op)) {
            return op;
        } else {
            var right = consumeTree();
            var left = consumeTree();
            return {
                name: op,
                left: left,
                right: right
            };
        }

    }
    return consumeTree();
}


var tree = MakeMeATree("23*5+5-");
console.log(JSON.stringify(tree));

/*

{
    "name":"-",
    "left":{
        "name":"+",
        "left":{
            "name":"*",
            "left":"2",
            "right":"3"
        },
        "right":"5"
    },
    "right":"5"
}

*/

Upvotes: 2

Related Questions