Create a fixed seven-node binary tree and render its shape.

Algorithm

The canonical tree is 4(2(1,3),6(5,7)), so this Perl DSA implementation can be compared directly with the rest of the DSA track.

node links A node stores one value plus references to its left and right children.

Basic Implementation

basic.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
sub node { my ($value, $left, $right) = @_; return { value => $value, left => $left, right => $right }; }
sub render {
    my ($node) = @_;
    return "_" unless defined $node;
    return "$node->{value}" unless defined $node->{left} || defined $node->{right};
    return "$node->{value}(" . render($node->{left}) . "," . render($node->{right}) . ")";
}
sub sample_tree {
    return node(4, node(2, node(1), node(3)), node(6, node(5), node(7)));
}
sub list_string { return "[" . join(", ", @_) . "]"; }
print render(sample_tree()) . "\n";
  1. node ← 1, tree ← 1

    1use strict;2use warnings;
    values this step1node1tree
  2. node ← 3, tree ← 1, 3

    1use strict;2use warnings;
    values this step3node1, 3tree
  3. node ← 2, tree ← 2(1,3)

    1use strict;2use warnings;
    values this step2node2(1,3)tree
  4. node ← 5, tree ← 2(1,3), 5

    1use strict;2use warnings;
    values this step5node2(1,3), 5tree
  5. node ← 7, tree ← 2(1,3), 5, 7

    1use strict;2use warnings;
    values this step7node2(1,3), 5, 7tree
  6. node ← 6, tree ← 2(1,3), 6(5,7)

    1use strict;2use warnings;
    values this step6node2(1,3), 6(5,7)tree
  7. node ← 4, tree ← 4(2(1,3),6(5,7))

    1use strict;2use warnings;
    values this step4node4(2(1,3),6(5,7))tree
  8. stdout ← 4(2(1,3),6(5,7))

    13sub list_string { return "[" . join(", ", @_) . "]"; }14print render(sample_tree()) . "\n";
    values this step4(2(1,3),6(5,7))stdout4(2(1,3),6(5,7))tree

Complexity

  • Time: O(n)
  • Space: O(n)

Implementation notes

  • node($value, $left, $right) returns a Perl hash reference: { value => $value, left => $left, right => $right }.
  • The node fields are read with hash-reference syntax such as $node->{value}, $node->{left}, and $node->{right}.
  • Leaves call node(1), node(3), node(5), and node(7) with no child arguments, so their left and right entries are undef.
  • sample_tree() builds the tree with nested constructor calls: node(4, node(2, node(1), node(3)), node(6, node(5), node(7))).
  • The trace creates leaf 1, leaf 3, then parent 2(1,3).
  • It then creates leaf 5, leaf 7, then parent 6(5,7).
  • The final root node is 4, with left child 2(1,3) and right child 6(5,7).
  • render returns _ for an undefined child, returns just the value for a leaf, and otherwise renders value(left,right).
  • Because all leaves are present in this sample, the final rendered tree has no _ placeholders: 4(2(1,3),6(5,7)).
  • print render(sample_tree()) . "\n" prints that compact tree string instead of Perl hash-reference internals.