Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Binary Search Tree Debug Question

by Anonymous Monk
on Aug 12, 2011 at 19:19 UTC ( #920074=note: print w/replies, xml ) Need Help??

in reply to Binary Search Tree Debug Question

Thanks for explaining, I sort of understand now the concept.

But is there a way to re-write the above code without using $_[0] = $tree?

I think that would really help in solidifying my understanding with this.

Replies are listed 'Best First'.
Re^2: Binary Search Tree Debug Question
by Tanktalus (Canon) on Aug 12, 2011 at 19:36 UTC

    A few possibilities. Here are two. The first is a minor change to the code:

    my $root; insert( \$root, 5 ); insert( \$root, 3 ); #... sub insert { my ($treeref, $value) = @_; my $tree = $$treeref; unless ($$treeref) { $tree = {}; #... $$treeref = $tree; } #...
    This just makes it explicit that the variable being passed in (by reference) may be modified.

    Another possibility is to have a "create tree" function for when the tree doesn't exist yet, and returns the initialised tree, possibly with the first value being required. The insert function would then need to tell if the tree is pristine and not yet populated (if the first value isn't required during create) to determine whether a new node was needed or not. The create-tree function would construct the tree - so we could call it a constructor. And we're basically at OO, all you have to do is bless the return :-)

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2022-12-02 09:30 GMT
Find Nodes?
    Voting Booth?