1
/ \
2 3
/ \ \
4 5 6
/
7
1234567
or
1
23
456
7
Solution:
# recursive version
def print_tree(L):
newL = []
for n in L:
print n
if n.left <> None:
newL.append(n.left)
if n.right <> None:
newL.append(n.right)
print_tree(newL)
print "\n"
Comment: we should use a queue structure and replace the loop with bottom() and the append with top() in order to avoid to have to create a list at each iteration
# iterative version
L = [n]
while (len(L)>0):
newL = []
for n in L:
print n
if n.left <> None:
newL.append(n.left)
if n.right <> None:
newL.append(n.right)
print "\n"
L = newL
Aucun commentaire:
Enregistrer un commentaire