# [Tutor] printing tree structure

Dave Angel davea at dejaviewphoto.com
Fri Jul 3 13:25:51 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
> Root:  e
> --Subtree:  []
> --Subtree:  []
> --Subtree:  ['c', ['f', [], []], []]
> Root:  c
> --Subtree:  ['f', [], []]
> Root:  f
> --Subtree:  []
> --Subtree:  []
> --Subtree:  []
>
>
Using tabs in Python source code is never a good idea, and mixing tabs
and spaces is likely to cause real problems, sometimes hard to debug.
That's not the problem here, but I wanted to mention it anyway.

The problem you have is the hierarchy doesn't show in the printout.
There are a few ways to indicate it, but the simplest is indentation,
the same as for Python source code.  Once things are indented, you'll
see that the line you commented as "this shouldn't be here" is correct
after all.

Add an additional parameter to the function to indicate level of
indenting.  Simplest way is to simply pass a string that's either 0
spaces, 4 spaces, etc.

L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]]
def printTree(L, indent=""):
for i in L:
if isinstance(i,str):
print indent, 'Root: ', i
else:
print indent, '--Subtree: ', i
printTree(i, indent+"    ")

printTree(L)

Root:  a
--Subtree:  ['b', ['d', [], []], ['e', [], []]]
Root:  b
--Subtree:  ['d', [], []]
Root:  d
--Subtree:  []
--Subtree:  []
--Subtree:  ['e', [], []]
Root:  e
--Subtree:  []
--Subtree:  []
--Subtree:  ['c', ['f', [], []], []]
Root:  c
--Subtree:  ['f', [], []]
Root:  f
--Subtree:  []
--Subtree:  []
--Subtree:  []

Now I don't know if that's what your list of lists was supposed to mean,
but at least it shows the structure of your printTree() loop.

DaveA
```