Trees
Build a Binary Tree
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), andnode(7)with no child arguments, so theirleftandrightentries areundef. 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, leaf3, then parent2(1,3). - It then creates leaf
5, leaf7, then parent6(5,7). - The final root node is
4, with left child2(1,3)and right child6(5,7). renderreturns_for an undefined child, returns just the value for a leaf, and otherwise rendersvalue(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.