Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
package bin_tree; #create a new instance of the bin_tree object, taking #$depth as an ar +gument... Create a binary tree, #recursively calling new() in order to create a node with #the desired + depth. sub new{ $class=shift; $depth=shift; #pull the class values and the depth beneath the nod +e desired, 0 for no lower nodes $self={value,a,b}; #make our object as an anonymous hash with keyw +ords but no values yet, that way the a and b keys (our branches) defa +ult evaluate to null $self->{value}=0; print $self->{value},"\n"; #just a debugging statement to try to f +igure out whats going on while ($depth >= 1){ #if we need to get deep, recursively call the + new() method, assigning the created objects to our a and b branches $depth--; $self->{a} = bin_tree->new($depth); #problem is here... the ne +w binary tree node never gets returned $self->{b} = bin_tree->new($depth); print $self->{a},"\n"; #debugging statement, this still evalua +tes to null, even though it should be set as an object reference now } bless $self, $class; #make object return $self; #return object } #5 minute depth test function, recursively runs down the "a" side of a + binary tree, returns the depth eventually sub depth_test{ $self=shift; print $i++,"\n"; if (defined $self->{a}){ $depth=$self->{a}->depth_test(); } return $depth+1; } #try to create a three node deep binary tree $bintree = bin_tree->new(3); print "Before:",$bintree->{a},"\n"; $deep = $bintree->depth_test(); print "Depth:",$deep,"\n"; #prove that new() call is just creating the + first level node) $bintree->{a} = bin_tree->new(); $bintree->{a}->{a} = bin_tree->new(); print "After:",$bintree->{a},"\n"; $deep = $bintree->depth_test(); print "Depth:",$deep,"\n"; #prove that when the code is outside of the + object methods, i can use my technique to build a tree
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: recursive creation of attached objects?
by chromatic (Archbishop) on Sep 14, 2012 at 00:22 UTC | |
|
Re: recursive creation of attached objects?
by remiah (Hermit) on Sep 14, 2012 at 04:06 UTC | |
by NetWallah (Canon) on Sep 14, 2012 at 04:54 UTC | |
by remiah (Hermit) on Sep 14, 2012 at 13:00 UTC | |
|
Re: recursive creation of attached objects?
by roboticus (Chancellor) on Sep 14, 2012 at 13:57 UTC | |
|
Re: recursive creation of attached objects?
by tobyink (Canon) on Sep 14, 2012 at 08:52 UTC | |
|
Re: recursive creation of attached objects?
by Marshall (Canon) on Sep 14, 2012 at 04:18 UTC | |
|
Re: recursive creation of attached objects?
by locked_user sundialsvc4 (Abbot) on Sep 15, 2012 at 16:15 UTC |