Node(3pm) | User Contributed Perl Documentation | Node(3pm) |
Tree::RedBlack::Node - Node class for Perl implementation of Red/Black tree
use Tree::RedBlack; my $t = new Tree::RedBlack; $t->insert(3, 'dog'); my $node = $t->node(3); $animal = $node->val;
A Tree::RedBlack::Node object supports the following methods:
You can use these methods to write utility routines for actions on red/black trees. For instance, here's a routine which writes a tree out to disk, putting the byte offsets of the left and right child records in the record for each node.
sub dump { my($node, $fh) = @_; my($left, $right); my $pos = tell $fh; print $fh $node->color ? 'R' : 'B'; seek($fh, 8, 1); print $fh $node->val; if ($node->left) { $left = dump($node->left,$fh); } if ($node->right) { $right = dump($node->right,$fh); } my $end = tell $fh; seek($fh, $pos+1, 0); print $fh pack('NN', $left, $right); seek($fh, $end, 0); $pos; }
You would call it like this:
my $t = new Tree::RedBlack; ... open(FILE, ">tree.dump"); dump($t->root,\*FILE); close FILE;
As another example, here's a simple routine to print a human-readable dump of the tree:
sub pretty_print { my($node, $fh, $lvl) = @_; if ($node->right) { pretty_print($node->right, $fh, $lvl+1); } print $fh ' 'x($lvl*3),'[', $node->color ? 'R' : 'B', ']', $node->key, "\n"; if ($node->left) { pretty_print($this->left, $fh, $lvl+1); } }
A cleaner way of doing this kind of thing is probably to allow sub-classing of Tree::RedBlack::Node, and then allow the Tree::RedBlack constructor to take an argument saying what class of node it should be made up out of. Hmmm...
Benjamin Holzman <bholzman@earthlink.net>
Tree::RedBlack
2022-10-22 | perl v5.34.0 |