Binary Tree Zigzag Traversal
Tree BFS
Problem
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
Thought Process

We can use a bool variable to denote when we switch directions
Solution
from collections import deque
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
result = []
queue = deque()
queue.append(root)
goLeft = True
while queue:
levelSize = len(queue)
currentLevel = deque()
for _ in range(levelSize):
currentNode = queue.popleft()
if goLeft:
currentLevel.append(currentNode.val)
if not goLeft:
currentLevel.appendleft(currentNode.val)
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
result.append(currentLevel)
goLeft = not goLeft
return result
#Depending on the bool variable, we will either append
#normally or in a "push back" fashion
#Time: O(n)
#Space: O(N)
PreviousBinary Tree Level Order Traversal II (Reverse Level Order Traversal)NextAverage of Levels in Binary Tree
Last updated
Was this helpful?