For a breadth first search , since I have to visit the left node first and then the right node and then repeat this process till I reach the very end , I fee its sort of tricky...
Not really, it just doesn’t lend itself to a recursive solution as depth-first traversal does. For the general algorithm, see the Wikipedia entry Tree_traversal#Breadth-first_2. Translated into Perl code matching the code you’ve shown for sub depthFirst, above, it will look like this (untested):
sub breadthFirst { my ($tree) = @_; return unless defined $tree; my @queue = ($tree); print $tree->{Value}; while (@queue) { my $node = shift @queue; print $node->{Value}; push @queue, $node->{Left} if defined $node->{Left}; push @queue, $node->{Right} if defined $node->{Right}; } }
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re^6: How do I create a binary tree?
by Athanasius
in thread How do I create a binary tree ?
by punitpawar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |