[Tutor] printing tree structure

Lie Ryan lie.1296 at gmail.com
Fri Jul 3 13:45:10 CEST 2009


karma wrote:
> Hi all ,
> 
> I have a nested list in the structure
> [root,[leftSubtree],[RightSubtree]] that I want to print out. I was
> thinking that a recursive solution would work here, but so far I can't
> quite get it working. This is what I have so far:
> 
> Can someone suggest whether this is suited to a recursive solution and
> if so, what am I doing wrong.
> 
> Thanks
> 
>>>> L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
>>>> def printTree(L):
> 	for i in L:
>            if isinstance(i,str):
> 		   print 'Root: ', i
> 	   else:
>               print '--Subtree: ', i
>               printTree(i)
> 
> 
>>>> printTree(L)
> Root:  a
> --Subtree:  ['b', ['d', [], []], ['e', [], []]]
> Root:  b
> --Subtree:  ['d', [], []]
> Root:  d
> --Subtree:  []
> --Subtree:  []
> --Subtree:  ['e', [], []] # this shouldn't be here

Why shouldn't it be there? Look more closely:

Root:  b
--Subtree:  ['d', [], []]
  ...
--Subtree:  ['e', [], []]
  ...

The program recurse correctly, however the way you're printing it is
misleading. When printing trees with arbitrary depth, you usually want
to keep track of the recursion depth. Something like this:

def print_tree(tree, depth=0):
    ...
    print_tree(node, depth + 1)
    ...



More information about the Tutor mailing list