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.

Basic Implementation

basic.pl
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";

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.
node links A node stores one value plus references to its left and right children.