LC103. Binary Tree Zigzag Level Order Traversal
#
Problem DescriptionSource: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
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).
For example: Given binary tree [3, 9, 20, null, null, 15, 7],
return its zigzag level order traversal as: [[3], [20, 9], [15, 7]].
#
Solution#
High level strategyOur strategy to solve this problem will be to conduct a breadth-first search. However, unlike an ordinary breadth-first search, we will only traverse from the left to right on even levels (including zero), and from the right to left on odd levels. The time complexity of this solution is O(n), where 'n' is equal to the number of nodes. The space complexity of this solution is O(logn), or O(h), where 'h' is equal to the height of the tree.
#
Code#
Other Solutions- We can potentially use a deque, insert it at head for odd levels, and tail for even levels
- Java
- Python