0

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;
        }
    } 
2
  • Trees are recursive data structures, so recursion is the natural way of dealing with them. Commented Dec 12, 2015 at 21:34
  • 2
    Put that var tree = new Object() (or bettter … = {}) inside your MakeMeATree function. Otherwise you have only one object that will repeatedly overwritten. Commented Dec 12, 2015 at 21:53

1 Answer 1

2

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"
}

*/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.