imashutosh51

ZigZag Tree Traversa

Jul 31st, 2022 (edited)
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1.  
  2. //Method 1:- Single pass O(n)
  3. /*
  4. Logic:
  5. We will use deque for storing the nodes of tree in level order and we will keep a flag which will alternate it's
  6. value at every level.Once you push the left and right node at back and pop from front.and second time
  7. you push right and left from from and pop from back.
  8. */
  9.  
  10. from collections import deque
  11. class Solution:
  12.    def zigZagTraversal(self, root):
  13.        if not root:
  14.            return []
  15.        ans = []
  16.        q = deque()
  17.        q.append(root)
  18.        flag = True
  19.        while q:
  20.            k = len(q)
  21.            for _ in range(k):
  22.                if flag:
  23.                    temp = q.popleft()
  24.                    ans.append(temp.data)
  25.                    if temp.left:
  26.                        q.append(temp.left)
  27.                    if temp.right:
  28.                        q.append(temp.right)
  29.                else:
  30.                    temp = q.pop()
  31.                    ans.append(temp.data)
  32.                    if temp.right:
  33.                        q.appendleft(temp.right)
  34.                    if temp.left:
  35.                        q.appendleft(temp.left)
  36.            flag = not flag
  37.        return ans
Advertisement
Add Comment
Please, Sign In to add comment