Binary Trees in Python

François Pinard pinard at
Sun Aug 21 14:52:10 CEST 2005

[Jorgen Grahn]

> Neither C++ nor Python has tree structures in their standard
> libraries.  I assume that's because there is no single interface that
> is proven to suit everybody's needs.

It is already easy writing "tree constants" using recursive tuples or
lists.  To process simple trees in Python, I usually subclass some
Node type from list, and write the traversal methods that suit the
application.  The sub-classing already allow for indexing sub-nodes by
"self[index]", and iterating over all by "for subnode in self:", etc.
In my experience, it all goes pretty easily, while staying simple.

However, things related to balancing, finding paths between nodes, or
searching for patterns, etc. may require more work.  There are surely
a flurry of tree algorithms out there.  What are the actual needs you
have, and would want to see covered by a library?

François Pinard

More information about the Python-list mailing list