用javascript打印树

Printing trees in javascript

本文关键字:打印 javascript      更新时间:2023-09-26

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

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

这将使您成为一棵树。

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