code-ninja has asked for the wisdom of the Perl Monks concerning the following question:
I tried implementing a binary tree in Perl without using any external library. My code follows. The problem is, it says:
in the traverse() function. I took help from algorithms in Perl book."Use of uninitialized value in numeric eq (==) at Tree.pl line 42. Use of uninitialized value in numeric eq (==) at Tree.pl line 42."
use strict; use warnings; sub search { my ($tree, $element) = @_; # we pass the root node and the element + to be found my $node; while($node = $$tree) { # $tree is a reference so we dereference i +t using $$. if($element == $node->{val}) { return($tree, $node); # return the subtree where the node +was found. } else { if($element < $node->{val}) { # go left $tree = \$node->{left}; # note that $tree is a referen +ce so we assign it a reference with '\' } else { $tree = \$node->{right}; } } } # we reach here iff there is no $element to be found # we politely suggest user that they may add the element at the gi +ven position. return ($tree, undef); } sub insert { my ($tree, $element) = @_; my $found; ($tree, $found) = search($tree, $element); unless($found) { $found = { left => undef, right => undef, val => $element, }; $$tree = $found; } return $found; } sub traverse { my $tree = shift; if($$tree->{left} == undef || $$tree->{right} == undef) { return; } traverse(\$tree->{left}); print $$tree->{val}; print "\n"; traverse(\$tree->{right}); } my @ele = [1, 2, 3, 4, 5]; my ($tree, $stat, $link); for my $ele (@ele) { ($stat, $link) = insert(\$tree, $ele); } traverse(\$tree);
As per my (limited) knowledge of Perl, I guess the search() and insert() function are correct, but I'm not sure.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Tree Data Structure
by kcott (Archbishop) on Dec 02, 2013 at 06:47 UTC | |
|
Re: Tree Data Structure
by Laurent_R (Canon) on Dec 02, 2013 at 07:06 UTC | |
|
Re: Tree Data Structure
by code-ninja (Scribe) on Dec 04, 2013 at 07:19 UTC |