Arrays 数组树读取

Arrays 数组树读取,arrays,function,recursion,tree,Arrays,Function,Recursion,Tree,我有一个要读取的数组: Tree [ "my", [ "name", [ "is", [ "Toto" ], [ "Bob" ] ] ], [ "algo", [ "doesn't", [ "work" ] ], [ "fail" ] ] ] 这应该是我的四句话: 我叫托

我有一个要读取的数组:

Tree [ "my",
       [ "name",
         [ "is",
           [ "Toto" ],
           [ "Bob"  ]
         ]
       ],
       [ "algo",
         [ "doesn't",
           [ "work" ]
         ],
         [ "fail" ]
       ]
     ]
这应该是我的四句话:

  • 我叫托托
  • 我叫鲍勃
  • 我的算法不行
  • 我的算法失败了
但是我的递归尝试没有成功。。。
谢谢。

因为您的结构是这样的:

node = [first, second]
first = string
second = [node, node, ...] or [string, string, ...]
您的伪代码如下所示:

struct node {string first; object second }

parse(string s, node tree)
{
    if (node.second is string)               //leaf of tree
        print(s + " " + node.second);
    else                                    //go deeper for each branch
        for each (b in node.second)
            parse(s + node.first, b);
}

main()
{
   parse(root.first, root.second);
}
在perl中:

sub act {
    my $data = shift;
    my $cb = shift;
    my @sentence = ();
    my $p;
    $p = sub{
            my $n = shift;
            if(defined $n && ref $n eq 'ARRAY'){
                    foreach my $item (@{$n}){
                            $p->($item);
                    }
                    if($#{$n} == 0){
                            &{$cb}(@sentence);
                    }
                    pop @sentence;
            } else{
                    push(@sentence, $n);
            }
    };
    $p->($data);
}

act($tree, sub {print join ' ', @_,"\n";});

但是基本上和你想的一样。

你在用什么语言?看起来你在[“algo”之前和[“Toto”]之后都丢了]我编辑。谢谢。我使用php。但是伪代码很好。我的结构更像:
节点=数组(字符串[,[node,[node,[…]])
where[]意思不是强制性的。我写的是相同的:任何一秒都可以是节点或字符串。节点意味着深度递归,字符串意味着句末OK,但我的理解是:第二秒是一个节点数组或字符串。这不适合我的情况。顺便说一句,我正在测试you'r递归函数的自适应,看看它是否合适。从Yarg函数自适应的解决方案: