I'm reading the Mastering Algorithms with Perl book (O'Reilly) and am wondering if someone could enlighten me on a part of a function where a compare is done. The code is:
sub basic_tree_find {
my ($tree_link, $target, $cmp) = @_;
my $node;
# $tree_link is the next pointer to be followed.
# It will be undef if we reach the bottom of the tree.
while ( $node = $$tree_link ) {
local $^W = 0; # no warnings, we expect undef values
my $relation = ( defined $cmp
? $cmp->( $target, $node->{val} )
: $target <=> $node->{val} );
# If we found it, return the answer.
return ($tree_link, $node) if $relation == 0;
# Nope - prepare to descend further - decide which way we go.
$tree_link = $relation > 0 ? \$node->{left} : \$node->{right};
}
# We fell off the bottom, so the element isn't there, but we
# tell caller where to create a new element (if desired).
return ($tree_link, undef);
}
The line that I'm questioning is
$tree_link = $relation > 0 ? \$node->{left} : \$node->{right};
$relation will be greater than 0 (read = 1) if $target is greater than $node->{val}. And this is where I'm confused. If that is the case wouldn't you want to traverse down $node->{right} instead of $node->{left}?
Thanks for any help given here :-)
Chris
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.