0

There is no indentation problem in the code

    class Node:
      def __init__(self,key):
        self.data=key
        self.left=None
        self.right=None
   def zig_zag(root):
    if not root:
        return
    s=[]
    l=1
    s.append(root)

    while s:
        q=[]
        if l%2==1:
            for i in reversed(s):
                print(i.data,end=' ')
                if i.left:q.append(i.left)
                if i.right:q.append(i.right)

        else:
            for i in s:
                print(i.data,end=' ')
                if i.left:q.append(i.left)
                if i.right:q.append(i.right)
        print(q)    
        s=q
        l+=1
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(7)
root.left.right=Node(6)
root.right.left=Node(5)
root.right.left=Node(4)
zig_zag(root)

The output i am getting is [1,2,3,4,6,7] instead of [1,2,3,4,5,6,7].can anybody explain that why its not appending 5 from the last branch of the tree

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Algorithm itself is fine.
But you have made a mistake in your "node adding code"
You are setting root.right.left twice

Change

root.right.left=Node(5)
root.right.left=Node(4)

to

root.right.left=Node(5)
root.right.right=Node(4)
Laser
  • 6,652
  • 8
  • 54
  • 85