in reply to A maybe(?) interesting comp-sci type problem
Tree : Node* Node : Term Tree | Term
It's not the ideal structure since a subtree needs to be distinguishable from a term and we need to look ahead, but it makes the tree more compact.
sub flatten { my ($tree) = @_; my @results; for (my $i=0; $i<@$tree; ) { my $has_subtree = ref($tree->[$i+1]); if ($has_subtree) { my $term = $tree->[$i+0]; my $subtree = $tree->[$i+1]; push @results, map { [ $term, @$_ ] } @{ flatten($subtree) }; $i += 2; } else { my $term = $tree->[$i+0]; push @results, [ $term ]; $i += 1; } } return \@results; } print("@$_\n") for @{ flatten($data_struct) };
Update: Small code reformat to resemble the tree structure description.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: A maybe(?) interesting comp-sci type problem
by tachyon-II (Chaplain) on May 06, 2008 at 10:12 UTC | |
by ikegami (Patriarch) on May 06, 2008 at 11:50 UTC |