Leser: 18
1
2
3
4
5
6
7
8
9
{
'12' => '11'
'11' => '10'
'10' => '888'
'17' => '42'
'999 ' => '42'
'42' => '4711'
'23' => '4711'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[
{ '4711' => {
'23' => '-1'
'42' => {
'999' => '-1'
'17' => '-1'
}
},
'888' => {
'10' => {
'11' => {
'12' => '-1'
}
}
}
}
]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $info = { '12' => '11', '11' => '10', '10' => '888', '17' => '42', '999 ' => '42', '42' => '4711', '23' => '4711', }; my %reverse; for my $key ( keys %{$info} ) { my $parent = $info->{$key}; push @{ $reverse{$parent} }, $key; } my @parents = values %{$info}; my @roots = grep{ !exists $info->{$_} }@parents; my %tree; for my $root ( @roots ) { fill_tree( \%tree, \%reverse, $root ); } print Dumper \%tree; sub fill_tree { my ($subtree,$reverse,$root) = @_; if ( exists $reverse->{$root} ) { $subtree->{$root} = {}; for my $node ( @{ $reverse->{$root} } ) { fill_tree( $subtree->{$root}, $reverse, $node ); } } else { $subtree->{$root} = -1; } }