Question: recursion and scope

adina_levin at mindspring.com adina_levin at mindspring.com
Mon Mar 25 21:26:30 EST 2002


Thank you very much, Terry.  That worked.

All I needed was the (return
max(self.right.howdeep(depth)),(self.left.howdeep(depth)))  (as adapted for
my implementation). I still have a counter, which works successfully for any
one side of the tree (though your version is nicer).

Why does this version work?  Why does the counter successfully keep count in
the recursion on one side of the tree, but lose count across sides of the
tree?

What scope principle, recursion concept, or logical step am I missing?

- Adina

Terry wrote:
>
> Perhaps you want something like the following (untested, adjust for
> your tree implementation):
>
> def maxdepth(tree):
>     if leaf(tree): return 1
>     elif onlyleftchild(tree): return maxdepth(leftchild) + 1
>     elif onlyritechild(tree): return maxdepth(ritechild) + 1
>     else return max(maxdepth(leftchild), maxdepth(ritechild)) + 1
>
> If you want to simultaneously count nodes, then you must return a
> tuple of (count,depth) and add a bit more calculation machinery.
>
> Terry J. Reedy

Adina wrote:

> > Hello, Pythonistas.
> >
> > I am attempting to teach myself some basic computer programming
> concepts
> > using Python.
> >
> > I'm currently extending the recursive binary tree program in
> Programming
> > Python to traverse the tree and count its depth. The program
> successfully
> > traverses the tree and counts the number of nodes.
> >
> > So far, though I haven't figured out how to calculate the "maximum
> depth" of
> > the tree without declaring "maxdepth" as a global variable.
> >
> > If maxdepth is declared as a local variable within the recursive
> method, it
> > gets re-set for each subtree.
> >
> > What am I missing?

>
>





More information about the Python-list mailing list