Trees
BST Insert
Insert values into a binary search tree by comparing at each node.
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.
binary search tree
Values smaller than a node go left; larger values go right.
Visual walkthrough
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(", ", @_) . "]"; }
sub insert { my ($root, $value) = @_; return node($value) unless defined $root; if ($value < $root->{value}) { $root->{left} = insert($root->{left}, $value); } else { $root->{right} = insert($root->{right}, $value); } return $root; }
my $root; for my $value (4, 2, 6, 1, 3, 5, 7) { $root = insert($root, $value); } print render($root) . "\n";
Complexity
- Time: O(h) per insert
- Space: O(n)
Implementation notes
node($value, $left, $right)returns a Perl hash reference:{ value => $value, left => $left, right => $right }.- Missing children are
undef;renderprints an undefined child as_. - Nodes are accessed with hash-reference syntax such as
$root->{value}and$root->{left}. my $rootstarts undefined, then each inserted value reassigns$root = insert($root, $value).inserttakes($root, $value)and returnsnode($value)when it reaches an undefined subtree.- The comparison is numeric:
if ($value < $root->{value}). - Smaller values recurse left with
$root->{left} = insert($root->{left}, $value). - All other values recurse right with
$root->{right} = insert($root->{right}, $value), so duplicates would follow the right branch in this source. - The checked insert order is
4, 2, 6, 1, 3, 5, 7. - The trace builds root
4, then attaches2on the left and6on the right, producing4(2,6). - Inserting
1follows4 -> left -> 2 -> left; inserting3follows4 -> left -> 2 -> right, giving4(2(1,3),6). - Inserting
5follows4 -> right -> 6 -> left; inserting7follows4 -> right -> 6 -> right, producing4(2(1,3),6(5,7)). print render($root) . "\n"prints that final tree string instead of dumping Perl object or hash-reference internals.- The replay also includes a sorted-insert contrast,
1(_,2(_,3(_,4))), to show the unbalanced height-4 shape without rotations.