Learn Code
Depth-First Search
Greedy Algorithms
Breadth-First Search
Zigzag Level Order
medium
DESCRIPTION (credit Leetcode.com)
Given the root of a binary tree, return the zigzag level-order traversal of its nodes' values.
The output should be a list of lists containing the values of the nodes at each level. The first list should contain the value of the root, the second list should contain the values of the nodes at the second level from right to left, the third list should contain the values of the third level from left to right, and so on.
Example 1:
Input:
Output: [[1], [4, 3], [2, 7], [8]]
Example 2:
Input:
Output: [[4], [7, 2], [1, 3, 6, 9], [2, 5]]
Explanation
Left to Right Processing
Right to Left Processing
from collections import dequeclass Solution:def zig_zag(self, root):if not root:return []nodes = []queue = deque([root])left_to_right = Truewhile queue:level_size = len(queue)nodes_for_level = deque()# process all nodes at this levelfor i in range(level_size):node = queue.popleft()if left_to_right:# add the node to the back of the listnodes_for_level.append(node.val)else:# add the node to the front of the listnodes_for_level.appendleft(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)# we've processed all nodes at the current level# add them to the output list and toggle left_to_right# to prepare for the next levelnodes.append(list(nodes_for_level))left_to_right = not left_to_rightreturn nodes
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(N) where N
is the number of nodes in the tree. We visit each node exactly once, and at each node, we perform a constant amount of work.
Space Complexity: O(N) where N
is the number of nodes in the tree. The output nodes
list contains each element in the tree exactly once.
Login to track your progress
Your account is free and you can post anonymously if you choose.