punitpawar has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
I know I had asked the question of how to create a Binary tree sometime back.
But wanted to know , if anyone can share with me , how I can create it BUT without using Recursion ? And how I can search for a given leaf node or a particular value in the tree ?

Replies are listed 'Best First'.
Re: Binary tree without recurssion
by NetWallah (Canon) on Dec 17, 2015 at 01:43 UTC
    Tree::Binary2 is simple enough, and does not require recursion to populate it.

    A search can be a simple grep:

    my @found_nodes= grep { $_->value =~ /LookForThis/ } $tree->traverse( + $tree->POST_ORDER );

            "I can cast out either one of your demons, but not both of them." -- the XORcist

Re: Binary tree without recurssion
by kennethk (Abbot) on Dec 17, 2015 at 01:53 UTC
    I'm guessing your cited previous query was How do I create a binary tree ?. Please link to previous questions ([id://1149515], Markup in the Monastery) so that those who might want to help you don't have to.

    Why do you want to avoid recursion? Performance reasons? Spec from instructor? Usually when people ask this sort of thing, it's an XY Problem.

    As Anonymous Monk cheerfully points out, recursion is just iteration. This is usually most easily done with Loop Control. If your tree isn't doubly linked, you'll probably also want to maintain a stack for traversing upwards. Recursion is usually taught first because it is more intuitive. If you share your implemented binary tree (wrapped in code tags), I'd be happy to show how to adapt your algorithm.

    Happy holidays.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: Binary tree without recurssion
by MidLifeXis (Monsignor) on Dec 17, 2015 at 14:42 UTC

    Depth first traversal can be accomplished with an array and unshift, breadth-first search via an array and push. Following pseudo-code converts to a flat list:

    # -*- pseudo-mode -*- traverse_queue = [ root ]; work_queue = []; while ( work_queue is_not empty ) { node = shift( traverse_queue ); push( work_queue, node ) if BFS; push/unshift( traverse_queue, children ); push( work_queue, node ) if DFS; }

    --MidLifeXis

Re: Binary tree without recurssion
by Anonymous Monk on Dec 16, 2015 at 23:52 UTC
    recursion is just iteration :)