Binary Tree Zigzag Level Order Traversal
Binary Tree Zigzag Level Order Traversal is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Tree Traversal Patterns (DFS & BFS) pattern, in the Level Order Traversal subpattern.
Problem statement
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 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 2000].
- -100 <= Node.val <= 100
Topics and companies
Topics: Tree, Breadth-First Search, Binary Tree.
Reported in interviews at Amazon, Microsoft, Bloomberg, Apple, Facebook, Qualtrics, eBay, Adobe, ByteDance, Google, Goldman Sachs, ServiceNow and others.
How to practise Binary Tree Zigzag Level Order Traversal on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(N), where N is the number of nodes in the tree. Each node is visited exactly once. time and O(N), for the result vector and the queue used for BFS traversal. In the worst case, the queue can hold up to N/2 nodes (for a complete binary tree's last level). space.
Open Binary Tree Zigzag Level Order Traversal in the code editor, or read the Binary Tree Zigzag Level Order Traversal editorial for a worked solution with its approach and complexity analysis.
Where Binary Tree Zigzag Level Order Traversal sits in the DSA pattern sheet
- Tree Traversal Patterns (DFS & BFS) pattern guide
- Level Order Traversal subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Binary Tree Zigzag Level Order Traversal
Other problems that use the same Level Order Traversal and Tree Traversal Patterns (DFS & BFS) techniques:
- Binary Tree Level Order Traversal — Medium, same subpattern
- Binary Tree Right Side View — Medium, same subpattern
- Find Largest Value in Each Tree Row — Medium, same subpattern
- Maximum Level Sum of a Binary Tree — Medium, same subpattern
- All Nodes Distance K in Binary Tree — Medium, same pattern
- Balanced Binary Tree — Easy, same pattern
Opening the problem
Progress is saved as you study.