Trees

Diez B. Roggisch deetsNOSPAM at web.de
Fri Feb 25 08:14:51 EST 2005


Alex Le Dain wrote:

> Is there a generic "tree" module that can enable me to sort and use
> trees (and nodes). Basically having methods such as .AddNode(),
> .GetAllChildren(), .FindNode() etc.


No. Usually, one uses the built-in python datastructures for this. E.g.

('root', [('child1', None), ('child2', None)])

Or writing a Node-class is also so straightforward that few care about them
being part of the core:

class Node(object):
   def __init__(self, payload, childs=None):
       self.payload = payload
       self.childs = childs

   def depth_first(self):
       if self.childs:
           for child in self.childs:
               for node in child.depth_first():
                   yield node
       yield self.payload



tree = Node('root', [Node('child1'), Node('child2')])

for n in tree.depth_first():
    print n
    
-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list