Ron Savage > Tree-Binary > Tree::Binary

Download:
Tree-Binary-1.06.tgz

Dependencies

Annotate this POD

CPAN RT

Open  0
View/Report Bugs
Module Version: 1.06   Source  

NAME ^

Tree::Binary - An Object Oriented Binary Tree for Perl

SYNOPSIS ^

  use Tree::Binary;

  # a tree representaion of the expression:
  #     ((2 + 2) * (4 + 5))
  my $btree = Tree::Binary->new("*")
                          ->setLeft(
                              Tree::Binary->new("+")
                                          ->setLeft(Tree::Binary->new("2"))
                                          ->setRight(Tree::Binary->new("2"))
                          )
                          ->setRight(
                              Tree::Binary->new("+")
                                          ->setLeft(Tree::Binary->new("4"))
                                          ->setRight(Tree::Binary->new("5"))
                          );
  # Or shown visually:
  #     +---(*)---+
  #     |         |
  #  +-(+)-+   +-(+)-+
  #  |     |   |     |
  # (2)   (2) (4)   (5)

  # get a InOrder visitor
  my $visitor = Tree::Binary::Visitor::InOrderTraversal->new();
  $btree->accept($visitor);

  # print the expression in infix order
  print $visitor->getAccumulation(); # prints "2 + 2 * 4 + 5"

  # get a PreOrder visitor
  my $visitor = Tree::Binary::Visitor::PreOrderTraversal->new();
  $btree->accept($visitor);

  # print the expression in prefix order
  print $visitor->getAccumulation(); # prints "* + 2 2 + 4 5"

  # get a PostOrder visitor
  my $visitor = Tree::Binary::Visitor::PostOrderTraversal->new();
  $btree->accept($visitor);

  # print the expression in postfix order
  print $visitor->getAccumulation(); # prints "2 2 + 4 5 + *"

  # get a Breadth First visitor
  my $visitor = Tree::Binary::Visitor::BreadthFirstTraversal->new();
  $btree->accept($visitor);

  # print the expression in breadth first order
  print $visitor->getAccumulation(); # prints "* + + 2 2 4 5"

  # be sure to clean up all circular references
  $btree->DESTROY();

DESCRIPTION ^

This module is a fully object oriented implementation of a binary tree. Binary trees are a specialized type of tree which has only two possible branches, a left branch and a right branch. While it is possible to use an n-ary tree, like Tree::Simple, to fill most of your binary tree needs, a true binary tree object is just easier to mantain and use.

Binary Tree objects are especially useful (to me anyway) when building parse trees of things like mathematical or boolean expressions. They can also be used in games for such things as descisions trees. Binary trees are a well studied data structure and there is a wealth of information on the web about them.

This module uses exceptions and a minimal Design By Contract style. All method arguments are required unless specified in the documentation, if a required argument is not defined an exception will usually be thrown. Many arguments are also required to be of a specific type, for instance the $tree argument to both the setLeft and setRight methods, must be a Tree::Binary object or an object derived from Tree::Binary, otherwise an exception is thrown. This may seems harsh to some, but this allows me to have the confidence that my code works as I intend, and for you to enjoy the same level of confidence when using this module. Note however that this module does not use any Exception or Error module, the exceptions are just strings thrown with die.

This object uses a number of methods copied from another module of mine, Tree::Simple. Users of that module will find many similar methods and behaviors. However, it did not make sense for Tree::Binary to be derived from Tree::Simple, as there are a number of methods in Tree::Simple that just wouldn't make sense in Tree::Binary. So, while I normally do not approve of cut-and-paste code reuse, it was what made the most sense in this case.

METHODS ^

new ($node)

The constructor accepts a $node value argument. The $node value can be any scalar value (which includes references and objects).

Mutators

setNodeValue ($node_value)

Sets the current Tree::Binary object's node to be $node_value

setUID ($uid)

This allows you to set your own unique ID for this specific Tree::Binary object. A default value derived from the object's hex address is provided for you, so use of this method is entirely optional. It is the responsibility of the user to ensure the value's uniqueness, all that is tested by this method is that $uid is a true value (evaluates to true in a boolean context). For even more information about the Tree::Binary UID see the getUID method.

setLeft ($tree)

This method sets $tree to be the left subtree of the current Tree::Binary object.

removeLeft

This method removed the left subtree of the current Tree::Binary object, making sure to remove all references to the current tree. However, in order to properly clean up and circular references the removed child might have, it is advised to call it's DESTROY method. See the "CIRCULAR REFERENCES" section for more information.

setRight ($tree)

This method sets $tree to be the right subtree of the current Tree::Binary object.

removeRight

This method removed the right subtree of the current Tree::Binary object, making sure to remove all references to the current tree. However, in order to properly clean up and circular references the removed child might have, it is advised to call it's DESTROY method. See the "CIRCULAR REFERENCES" section for more information.

Accessors

getUID

This returns the unique ID associated with this particular tree. This can be custom set using the setUID method, or you can just use the default. The default is the hex-address extracted from the stringified Tree::Binary object. This may not be a universally unique identifier, but it should be adequate for at least the current instance of your perl interpreter. If you need a UUID, one can be generated with an outside module (there are many to choose from on CPAN) and the setUID method (see above).

getParent

Returns the parent of the current Tree::Binary object.

getDepth

Returns the depth of the current Tree::Binary object within the larger hierarchy.

getNodeValue

Returns the node value associated with the current Tree::Binary object.

getLeft

Returns the left subtree of the current Tree::Binary object.

getRight

Returns the right subtree of the current Tree::Binary object.

Informational

isLeaf

A leaf is a tree with no branches, if the current Tree::Binary object does not have either a left or a right subtree, this method will return true (1), otherwise it will return false (0).

hasLeft

This method will return true (1) if the current Tree::Binary object has a left subtree, otherwise it will return false (0).

hasRight

This method will return true (1) if the current Tree::Binary object has a right subtree, otherwise it will return false (0).

isRoot

This method will return true (1) if the current Tree::Binary object is the root (it does not have a parent), otherwise it will return false (0).

Recursive Methods

traverse ($func)

This method takes a single argument of a subroutine reference $func. If the argument is not defined and is not in fact a CODE reference then an exception is thrown. The function is then applied recursively to both subtrees of the invocant. Here is an example of a traversal function that will print out the hierarchy as a tabbed in list.

  $tree->traverse(sub {
        my ($_tree) = @_;
        print (("\t" x $_tree->getDepth()), $_tree->getNodeValue(), "\n");
        });
mirror

This method will swap the left node for the right node and then do this recursively on down the tree. The result is the tree is a mirror image of what it was. So that given this tree:

     +---(-)---+
     |         |
  +-(*)-+   +-(+)-+
  |     |   |     |
 (1)   (2) (4)   (5)

Calling mirror will result in your tree now looking like this:

     +---(-)---+
     |         |
  +-(+)-+   +-(*)-+
  |     |   |     |
 (5)   (4) (2)   (1)

It should be noted that this is a destructive action, it will alter your current tree. Although it is easily reversable by simply calling mirror again. However, if you are looking for a mirror copy of the tree, I advise calling clone first.

  my $mirror_copy = $tree->clone()->mirror();

Of course, the cloning operation is a full deep copy, so keep in mind the expense of this operation. Depending upon your needs it may make more sense to call mirror a few times and gather your results with a Visitor object, rather than to clone.

size

Returns the total number of nodes in the current tree and all its sub-trees.

height

Returns the length of the longest path from the current tree to the furthest leaf node.

Misc. Methods

accept ($visitor)

It accepts either a Tree::Binary::Visitor::* object, or an object who has the visit method available (tested with $visitor->can('visit')). If these qualifications are not met, and exception will be thrown. We then run the Visitor's visit method giving the current tree as its argument.

clone

The clone method does a full deep-copy clone of the object, calling clone recursively on all its children. This does not call clone on the parent tree however. Doing this would result in a slowly degenerating spiral of recursive death, so it is not recommended and therefore not implemented. What it does do is to copy the parent reference, which is a much more sensible act, and tends to be closer to what we are looking for. This can be a very expensive operation, and should only be undertaken with great care. More often than not, this method will not be appropriate. I recommend using the cloneShallow method instead.

cloneShallow

This method is an alternate option to the plain clone method. This method allows the cloning of single Tree::Binary object while retaining connections to the rest of the tree/hierarchy. This will attempt to call clone on the invocant's node if the node is an object (and responds to $obj->can('clone')) otherwise it will just copy it.

DESTROY

To avoid memory leaks through uncleaned-up circular references, we implement the DESTROY method. This method will attempt to call DESTROY on each of its children (if it as any). This will result in a cascade of calls to DESTROY on down the tree. It also cleans up it's parental relations as well.

Because of perl's reference counting scheme and how that interacts with circular references, if you want an object to be properly reaped you should manually call DESTROY. This is especially nessecary if your object has any children. See the section on "CIRCULAR REFERENCES" for more information.

fixDepth

For the most part, Tree::Binary will manage your tree's depth fields for you. But occasionally your tree's depth may get out of place. If you run this method, it will traverse your tree correcting the depth as it goes.

CIRCULAR REFERENCES ^

Perl uses reference counting to manage the destruction of objects, and this can cause problems with circularly referencing object like Tree::Binary. In order to properly manage your circular references, it is nessecary to manually call the DESTROY method on a Tree::Binary instance. Here is some example code:

  # create a root
  my $root = Tree::Binary->new()

  { # create a lexical scope

      # create a subtree (with a child)
      my $subtree = Tree::Binary->new("1")
                          ->setRight(
                              Tree::Binary->new("1.1")
                          );

      # add the subtree to the root
      $root->setLeft($subtree);

      # ... do something with your trees

      # remove the first child
      $root->removeLeft();
  }

At this point you might expect perl to reap $subtree since it has been removed from the $root and is no longer available outside the lexical scope of the block. However, since $subtree itself has a subtree, its reference count is still (at least) one and perl will not reap it. The solution to this is to call the DESTROY method manually at the end of the lexical block, this will result in the breaking of all relations with the DESTROY-ed object and allow that object to be reaped by perl. Here is a corrected version of the above code.

  # create a root
  my $root = Tree::Binary->new()

  { # create a lexical scope

      # create a subtree (with a child)
      my $subtree = Tree::Binary->new("1")
                          ->setRight(
                              Tree::Binary->new("1.1")
                          );

      # add the subtree to the root
      $root->setLeft($subtree);

      # ... do something with your trees

      # remove the first child and capture it
      my $removed = $root->removeLeft();

      # now force destruction of the removed child
      $removed->DESTROY();
  }

As you can see if the corrected version we used a new variable to capture the removed tree, and then explicitly called DESTROY upon it. Only when a removed subtree has no children (it is a leaf node) can you safely ignore the call to DESTROY. It is even nessecary to call DESTROY on the root node if you want it to be reaped before perl exits, this is especially important in long running environments like mod_perl.

OTHER TREE MODULES ^

As crazy as it might seem, there are no pure (non-search) binary tree implementations on CPAN (at least not that I could find). I found several balanaced trees of one kind or another (see the OTHER TREE MODULES section of the Tree::Binary::Search documentation for that list). The closet thing I could find was the Tree module described below.

Tree

I cannot tell for sure, but this module may include a non-search binary tree in it. Its documentation is beyond non-existant, and I gave up after reading about 3/4 of the source code. It was uploaded in October 1999 and as far as I can tell it has ever been updated (the file modification dates are 05-Jan-1999). There is no actual file called Tree.pm, so CPAN can find no version number. It has no MANIFEST, README of Makefile.PL, so installation is entirely manual. Some of it even appears to have been written by Mark Jason Dominus, as far back as 1997 (possibly the source code from an old TPJ article on B-Trees by him).

SEE ALSO ^

This module is part of a larger group, which are listed below.

Tree::Binary::Search
Tree::Binary::VisitorFactory
Tree::Binary::Visitor::BreadthFirstTraversal
Tree::Binary::Visitor::PreOrderTraversal
Tree::Binary::Visitor::PostOrderTraversal
Tree::Binary::Visitor::InOrderTraversal

BUGS ^

None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it.

CODE COVERAGE ^

I use Devel::Cover to test the code coverage of my tests, below is the Devel::Cover report on this module test suite.

 -------------------------------------------- ------ ------ ------ ------ ------ ------ ------
 File                                           stmt branch   cond    sub    pod   time  total
 -------------------------------------------- ------ ------ ------ ------ ------ ------ ------
 Tree/Binary.pm                                100.0   97.3   93.9  100.0  100.0   71.7   98.7
 Tree/Binary/Search.pm                          99.0   90.5   81.2  100.0  100.0   13.9   95.1
 Tree/Binary/Search/Node.pm                    100.0  100.0   66.7  100.0  100.0   11.7   98.2
 Tree/Binary/VisitorFactory.pm                 100.0  100.0    n/a  100.0  100.0    0.5  100.0
 Tree/Binary/Visitor/Base.pm                   100.0  100.0   66.7  100.0  100.0    0.5   96.4
 Tree/Binary/Visitor/BreadthFirstTraversal.pm  100.0  100.0  100.0  100.0  100.0    0.0  100.0
 Tree/Binary/Visitor/InOrderTraversal.pm       100.0  100.0  100.0  100.0  100.0    1.1  100.0
 Tree/Binary/Visitor/PostOrderTraversal.pm     100.0  100.0  100.0  100.0  100.0    0.3  100.0
 Tree/Binary/Visitor/PreOrderTraversal.pm      100.0  100.0  100.0  100.0  100.0    0.3  100.0
 -------------------------------------------- ------ ------ ------ ------ ------ ------ ------
 Total                                          99.6   94.4   88.8  100.0  100.0  100.0   97.4
 -------------------------------------------- ------ ------ ------ ------ ------ ------ ------

Repository ^

https://github.com/ronsavage/Tree-Binary

AUTHOR ^

stevan little, <stevan@iinteractive.com>

COPYRIGHT AND LICENSE ^

Copyright 2004, 2005 by Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

syntax highlighting: