in reply to A maybe(?) interesting comp-sci type problem

The structure can be defined as
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

    Hmm, this returns 13 x 5 = 65 elements from 35 original values

      What are you implying? I don't think anything can be derived from 35 since it's not a full tree.

      I count 13 leaves, so there should be 13 results.
      And every leaf is at depth 5, so each result should be of length 5.