数组树阅读

时间:2011-09-21 10:14:29

标签: arrays function recursion tree

我想要阅读这个数组:

Tree [ "my",
       [ "name",
         [ "is",
           [ "Toto" ],
           [ "Bob"  ]
         ]
       ],
       [ "algo",
         [ "doesn't",
           [ "work" ]
         ],
         [ "fail" ]
       ]
     ]

这应该给我4个句子:

  • 我的名字是Toto
  • 我叫鲍勃
  • 我的算法不起作用
  • 我的算法失败

但我的递归尝试没有成功...... 谢谢。

2 个答案:

答案 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";});

但它与你想出的基本相同。