LeetCode 103. Binary Tree Zigzag Level Order Traversal

Description

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

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: [,[20,9],[15,7]]

Example 2:

Input: root = 
Output: []

Example 3:

Input: root = []
Output: []

Constraints:

• The number of nodes in the tree is in the range [0, 2000].
• -100 <= Node.val <= 100

Explanation

Use breadth-first search and order the nodes differently on odd or even levels.

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: TreeNode) -> List[List[int]]:
results = []

if not root:
return results

queue = []
queue.append(root)

level_index = 0

while queue:

size = len(queue)
level = []

for i in range(size):
node = queue.pop(0)
if level_index % 2 != 0:
level.insert(0, node.val)
else:
level.append(node.val)

if node.left:
queue.append(node.left)

if node.right:
queue.append(node.right)

results.append(level)
level_index += 1

return results
• Time complexity: O(N).
• Space complexity: O(N).