Advertisement
rishu110067

Untitled

Jan 23rd, 2022
834
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. import collections
  3.  
  4. def zigzag_level_order_traversal(root):
  5.     if root is None:
  6.         return []
  7.        
  8.     result = []
  9.     q = collections.deque([root]) #insert the first node
  10.    
  11.     rtol = False
  12.     while len(q) != 0:
  13.        
  14.         numnodes = len(q) # get the number of nodes in deque
  15.         temp = []
  16.  
  17.         for _ in range(numnodes):
  18.            
  19.             node = q.popleft() # store the first val of the deque in node
  20.             temp.append(node.label) #append to the temp for that level
  21.            
  22.             if node.left_ptr is not None:
  23.                 q.append(node.left_ptr)
  24.                
  25.             if node.right_ptr is not None:
  26.                 q.append(node.right_ptr)
  27.  
  28.         if rtol is True:
  29.             temp.reverse()
  30.         rtol = not rtol
  31.        
  32.         result.append(temp)
  33.        
  34.     return (result)
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement