简体   繁体   中英

I am trying zig zag traversal of a binary tree. it's not printing 5 of the last branch,why?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM