Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^4: How do I create a binary tree ?

by Anonymous Monk
on Dec 07, 2015 at 14:26 UTC ( [id://1149581]=note: print w/replies, xml ) Need Help??


in reply to Re^3: How do I create a binary tree ?
in thread How do I create a binary tree ?

Thanks for the response. I see that the link has been removed. Going forward I will keep this in mind.

Replies are listed 'Best First'.
Re^5: How do I create a binary tree ?
by punitpawar (Sexton) on Dec 21, 2015 at 19:56 UTC
    Hello ,
    How can I do a Breadth First search for a binary tree in perl ?
    For the above code how can I go ahead and create a subroutine for Breadth First search ?
    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...
    I have written a snippet below for "Depth First" search , but not able to think for a Breadth first search
    sub depthFirst { my ($tree) =@_; return unless ($tree); print $tree->{Value}; depthFirst($tree->{Left}); depthFirst($tree->{Right}); }
      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,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1149581]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-20 02:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found