Trees
Level-Order Traversal
Visit a tree breadth-first with a queue.
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(", ", @_) . "]"; }
my @queue = (sample_tree()); my @output; while (@queue) { my $node = shift @queue; push @output, $node->{value}; push @queue, $node->{left} if defined $node->{left}; push @queue, $node->{right} if defined $node->{right}; } print list_string(@output) . "\n";
Complexity
- Time: O(n)
- Space: O(w) queue space
Implementation notes
- Nodes are Perl hash references with
value,left, andrightkeys, built bynode($value, $left, $right). - Node fields are accessed with hash-reference syntax such as
$node->{value}and$node->{left}. sample_tree()builds the fixed tree4(2(1,3),6(5,7)).my @queue = (sample_tree())stores the root node reference in a Perl array used as the traversal queue.my @outputcollects visited node values.- The loop condition
while (@queue)uses@queuein scalar context, so it means "while the queue has length". - Dequeue uses
my $node = shift @queue, removing the front node reference. - Visit writes the scalar value with
push @output, $node->{value}. - Child enqueue checks
defined $node->{left}anddefined $node->{right}so undefined children are skipped instead of queued. - The trace starts with queue
[4]. - Dequeueing
4outputs[4]and enqueues[2, 6]. - Dequeueing
2outputs[4, 2]and leaves queue[6, 1, 3]. - Dequeueing
6outputs[4, 2, 6]and leaves queue[1, 3, 5, 7]. - The leaf visits then drain the queue through
[3, 5, 7],[5, 7],[7], and finally[]. list_string(@output)joins the visited values with", ", so the final print is[4, 2, 6, 1, 3, 5, 7].
level order
Level-order traversal uses a queue to visit shallower nodes first.