Question: recursion and scope

Terry Reedy tejarex at yahoo.com
Mon Mar 25 14:18:32 EST 2002


<adina_levin at mindspring.com> wrote in message
news:a7nrl8$snv$1 at slb6.atl.mindspring.net...
> 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?

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





More information about the Python-list mailing list