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.
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";
node ← 1, tree ← 1
1use strict;2use warnings;values this step1node1treenode ← 3, tree ← 1, 3
1use strict;2use warnings;values this step3node1, 3treenode ← 2, tree ← 2(1,3)
1use strict;2use warnings;values this step2node2(1,3)treenode ← 5, tree ← 2(1,3), 5
1use strict;2use warnings;values this step5node2(1,3), 5treenode ← 7, tree ← 2(1,3), 5, 7
1use strict;2use warnings;values this step7node2(1,3), 5, 7treenode ← 6, tree ← 2(1,3), 6(5,7)
1use strict;2use warnings;values this step6node2(1,3), 6(5,7)treenode ← 4, tree ← 4(2(1,3),6(5,7))
1use strict;2use warnings;values this step4node4(2(1,3),6(5,7))treestdout ← 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), 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.