0

I am performing the zig zag level order traversal of the binary tree.

def zigZagTraversal(self, root):
    if root is None:
        return []
    s1=[root]
    s2=[]
    level=[]
    res=[]
    while s1 or s2:
        while s1:
            root=s1.pop()
            level.append(root.data)
            #first move from left ot right
            if root.left!=None:
                s2.append(root.left)
            if root.right!=None:
                s2.append(root.right)
                
        res.append(level)
        level=[]
        #now we will run the while loop for the other stacks
        while s2:
            root=s2.pop()
            level.append(root.data)
            #here move from right to left
            if root.right!=None:
                s1.append(root.right)
            if root.left!=None:
                s1.append(root.left)
        if level!=[]:
            res.append(level)
            level=[]
    return res

My output [3] [1, 2] **expected output ** 3 1 2

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • See https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists – Orius Feb 13 '22 at 06:29
  • More than a few elements are undefined in your current code snippet. Can you pull together a [mre] including some sample input data/function usage that we can copy into a clean workspace and reproduce the current behaviour? – Henry Ecker Feb 13 '22 at 06:41
  • Works fine using the link shared by Orius. – shalini choudhary Feb 13 '22 at 07:25
  • Does this answer your question? [Flattening a nested list in Python](https://stackoverflow.com/questions/62433745/flattening-a-nested-list-in-python) – Artyom Vancyan Feb 13 '22 at 14:45

1 Answers1

0

You could write a loop to flatten the list:

res = [[3],[1,2]]
for i,_ in enumerate(res):
    while isinstance(res[i],list):
        res[i:i+1] = res[i]

print(*res)
3 1 2

alternatively you could extend res instead of appending a sub-list in your own code:

res.extend(level) # instead of res.append(level)
Alain T.
  • 40,517
  • 4
  • 31
  • 51