in reply to tree with variable number of children
I'd be inclined to use hashes instead of arrays. The code simplifies somewhat:
use strict; use warnings; use Data::Dump::Streamer; my $s = "f b, b c, a c, e b, d a, g a"; my %children = map {split ' ', $_} split ',', $s; my %tree; # Build the tree push @{$tree{$children{$_}}}, $_ for keys %children; # Find the root my $root = (keys %children)[0]; while ($root) { last unless exists $children{$root}; $root = $children{$root}; } print "Root is $root\n"; Dump (\%tree);
Prints:
Root is c $HASH1 = { a => [ 'g', 'd' ], b => [ 'e', 'f' ], c => [ 'a', 'b' ] };
|
|---|