use Data::Dumper; # 1 # / \ # 2 3 # / \ #4 5 my ($root) = (@ARGV); if (!$root) { $root = 1; } $ret = get_all_paths($root); print Dumper($ret); sub get_branches { my ($i) = (@_); if ($i==1) { return [2, 3]; } if ($i==2) { return [4, 5]; } return []; } sub get_all_paths { my ($root) = (@_); my @allroutes; my $branches; $branches = get_branches($root); if (@$branches == 0) { # we've reached the end/leaf node return [ [$root]]; } foreach my $branch (@$branches) { my $partial_routes = get_all_paths($branch); foreach my $route (@$partial_routes) { my @newroute; push @newroute, $root; push @newroute, @$route; push @allroutes, \@newroute; } } return \@allroutes; }