我想要阅读这个数组:
Tree [ "my",
[ "name",
[ "is",
[ "Toto" ],
[ "Bob" ]
]
],
[ "algo",
[ "doesn't",
[ "work" ]
],
[ "fail" ]
]
]
这应该给我4个句子:
但我的递归尝试没有成功...... 谢谢。
答案 0 :(得分:0)
因为你的结构是这样的:
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);
}
答案 1 :(得分:0)
在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";});
但它与你想出的基本相同。