Javascript n-ary树InOrder函数

时间:2016-10-22 03:35:37

标签: javascript tree binary-tree binary-search-tree inorder

我构建了一个从二叉树(InOrder)中获取值的函数。现在我想修改该函数,以便它可以与n-ary树一起使用。我很感激你的帮助。

function stringFromInOrder(tree, position) {
    if (!tree) {
        return "";  
    }else if(tree.value === ""){
            return false;
        }
    return  stringFromInOrder(tree.left) + tree.value + stringFromInOrder(tree.right) ;
}

1 个答案:

答案 0 :(得分:0)

如果你想坚持递归:

function stringFromInOrder(tree, position) {
    if (!tree) {
        return "";  
    }else if(tree.value === ""){
            return false;
        }
    var s = 0;
    var i = 0
    while (i < tree.children.count)
    {
       s += stringFromInOrder(tree.children[i]);
       i++;
    }
    return  tree.value + s;
}