package bin_tree; #create a new instance of the bin_tree object, taking #\$depth as an argument... 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 node desired, 0 for no lower nodes \$self={value,a,b}; #make our object as an anonymous hash with keywords but no values yet, that way the a and b keys (our branches) default evaluate to null \$self->{value}=0; print \$self->{value},"\n"; #just a debugging statement to try to figure 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 new binary tree node never gets returned \$self->{b} = bin_tree->new(\$depth); print \$self->{a},"\n"; #debugging statement, this still evaluates 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