在javascript中打印树

时间:2015-12-12 21:30:02

标签: javascript

我需要打印我的树,但我不知道该怎么做。我猜我可能会使用递归。我想知道是否有更简单的方法?这是代码。

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

我也不确定回归,我的意思是我应该两次使用return tree吗?还是到最后?

UPD: 这个功能我猜是

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

1 个答案:

答案 0 :(得分:2)

这会让你成为一棵树。

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

*/