RogerBW's Blog

Perl Weekly Challenge 57: tree inversion and unique prefixes 05 May 2020

I’ve been doing the Perl Weekly Challenges. The latest involved inverting a binary tree and finding unique prefixes.

You are given a full binary tree of any height.

Write a script to invert the tree, by mirroring the children of every node, from left to right.

The input can be any sensible machine-readable binary tree format of your choosing, and the output should be the same format.

Well then, I'll just use the format I wrote for last week's problem… which also works on non-binary trees, which is handy.

my @tree=qw(1 .2 ..4 ..5 .3 ..6 ..7);

And the interpreter I wrote then too.

my %tree;
  my @parent;
  foreach my $index (0..$#tree) {
    $tree[$index] =~ /^(\.*)(\d+)/;
    my ($depth,$val)=(length($1),$2);
    if ($depth>0) {
      push @{$tree{$parent[$depth-1]}{children}},$index;

The reversal is trivial:

foreach my $k (keys %tree) {
  if (exists $tree{$k}{children}) {
    @{$tree{$k}{children}}=reverse @{$tree{$k}{children}};

Then it's just a recursion to print the thing in some sort of good order.


sub tdump {
  my ($tree,$index,$depth)=@_;
  print '.' x $depth,$tree->{$index}{value},"\n";
  if (exists $tree->{$index}{children}) {
    foreach my $c (@{$tree->{$index}{children}}) {


In addition to the above, you may wish to pretty-print your binary tree in a human readable text-based format similar to the following:

  /  \
 3    2
/ \  / \

7 6 5 4

This is actually distinctly more fiddly. And here I do give up generality and rely on the tree being both full and binary; there are no leaf nodes at less than the maximum depth. I also rely on each tree value being a single character.

my %d;
my @t=([0,0]);
while (@t) {
  my $i=shift @t;
  my ($index,$depth)=@{$i};
  push @{$d{$depth}},$index;
  if (exists $tree{$index}{children}) {
    push @t,map {[$_,$depth+1]} @{$tree{$index}{children}};

my %c;
my @out;
my $d=max(keys %d);
while (1) {
  my @r;
  if (@out) {
    foreach my $i (0..$#{$d{$d}}) {
      my $si=$tree{$d{$d}[$i]}{children}[0] or die "need a full tree";
  } else {
    my $noffsets=scalar @{$d{$d}};
    my $j=-2;
    while ($noffsets) {
      push @r,$j;
      push @r,$j;
  my $str=' ' x (max @r);
  my $stru=' ' x ((max @r)-1);
  my $m=0;
  foreach my $i (0..$#{$d{$d}}) {
    unless ($d==0) {
      if ($m%2==0) {
      } else {
  unshift @out,$str;
  if ($d>0) {
    unshift @out,$stru;
  if ($d==0) {

print map {"$_\n"} @out;

Part 2 was very much simpler:

Write a script to find the shortest unique prefix for each each word in the given list. The prefixes will not necessarily be of the same length.

Sample Input

[ "alphabet", "book", "carpet", "cadmium", "cadeau", "alpine" ]

Expected Output [ "alph", "b", "car", "cadm", "cade", "alpi" ]

my @input=qw(alphabet book carpet cadmium cadeau alpine);

OK, so let's make these into a hash. (In Perl6 I'd use a Set, but I had lots of other things to do so I didn't bother with P6 for either of this week's challenges.)

Then for each candidate length N I fill another hash keyed on the first N letters; any N-letter tuple that's unique, i.e. there's only one entry under it, can be dumped and the input word deleted for faster checking of the rest.

my @out;
my %input=map {$_ => 1} @input;
my $len=1;
while (%input) {
  my %k;
  map {push @{$k{substr($_,0,$len)}},$_} keys %input;
  foreach my $k (keys %k) {
    if (scalar keys @{$k{$k}}==1) {
      push @out,$k;
      delete $input{$k{$k}[0]};

I could order them by the original input, but didn't.

print map {"$_\n"} sort @out;

This will fail in the case where one word is the same as the start of another (e.g. "branch" and "branching"), but the problem itself breaks down in that case. A terminator character (i.e. something that appears in no word and can be added to the end of each) would make a solution possible.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1