"karma" <dorjeta...@googlemail.com> wrote

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

Yes certainly

if so, what am I doing wrong.

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:  []

This is the end of the recursive call to printTree( ['d', [ [], [] ] ]

--Subtree:  ['e', [], []] # this shouldn't be here

This is the next element in printTree( ['d', [], []], ['e', [], []] )

Root:  e

This is the start of printTree( ['e', [], [] ]  )

--Subtree:  []
--Subtree:  []

Now why do you think the line you highlighted is an error?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to