MediumNo. 0103
Binary Tree Zigzag Level Order Traversal — LeetCode 103 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Breadth-First Search, Binary Tree
- On a study list
- Top Interview 150
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Example
- Input
- root = [3,9,20,null,null,15,7]
- Output
- [[3],[20,9],[15,7]]
Python solution
# 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: Optional[TreeNode]) -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
ans = []
left = 1
while q:
t = []
for _ in range(len(q)):
node = q.popleft()
t.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(t if left else t[::-1])
left ^= 1
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 103. Binary Tree Zigzag Level Order Traversal is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0102 | Binary Tree Level Order Traversal | Medium |
| 0107 | Binary Tree Level Order Traversal II | Medium |
| 0919 | Complete Binary Tree Inserter | Medium |
| 0958 | Check Completeness of a Binary Tree | Medium |
| 1609 | Even Odd Tree | Medium |
| 2471 | Minimum Number of Operations to Sort a Binary Tree by Level | Medium |
Frequently asked questions
- How hard is LeetCode 103. Binary Tree Zigzag Level Order Traversal?
LeetCode 103. Binary Tree Zigzag Level Order Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 103. Binary Tree Zigzag Level Order Traversal?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 103. Binary Tree Zigzag Level Order Traversal?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 103. Binary Tree Zigzag Level Order Traversal cover?
LeetCode 103. Binary Tree Zigzag Level Order Traversal is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.