pythonic way of depth first and breadth first tree iterators

Dave Reed dreed at capital.edu
Fri Mar 15 20:37:59 EST 2002


We're planning to use Python in our CS1 and CS2 courses next year so
I'm beginning to think about the issues for these courses.

http://www.python.org/doc/current/lib/typeiter.html states:

  If a container supports different types of iteration, additional
  methods can be provided to specifically request iterators for those
  iteration types. (An example of an object supporting multiple forms
  of iteration would be a tree structure which supports both
  breadth-first and depth-first traversal.)

I don't quite understand exatly what that is saying - what would be
the pythonic way of defining/calling separate breadth first and depth
first iterators for a binary tree class - i.e., is there a way to
indicate which method to use when you make the call to iter() so that
I could do something like: for node in tree('depth'):

and

for node in tree('breadth'):

Or is that just implying that I can make a depth first class iterator
class and breadth first iterator class that both support the
corresponding next() method and do something like:

d = DepthIter(tree) 
for node in d:

where DepthIter is a class that takes a tree as a parameter to its
constructor and has a next() method that returns the nodes in a depth
first manner. And similarly, write a BreadthIter class?

Thanks,
Dave




More information about the Python-list mailing list