Skip to main content

Binary Tree Zigzag Level Order Traversal

Question

What is the most efficient algorithm for traversing a binary tree in a zigzag level order?

Example 1
Input: 
3
/ \
9 20
/ \
15 7

Output: [[3], [20, 9], [15, 7]]

Solution

all//Binary Tree Zigzag Level Order Traversal.py
import collections

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root):
result = []
if not root:
return result
q = collections.deque([root])
count = 0
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if count % 2 == 0:
result.append(level)
else:
result.append(level[::-1])
count += 1
return result