Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nhudinhtuan/59006787bf5199e08e354f627229a4ee to your computer and use it in GitHub Desktop.
Save nhudinhtuan/59006787bf5199e08e354f627229a4ee to your computer and use it in GitHub Desktop.
Tree traversal - level order
from collections import deque
def levelorder_traversal_iterating(root):
if not root:
return []
result = []
# using queue
queue = deque([root])
while queue:
# start a new level array
result.append([])
current_level_size = len(queue)
# visit all items in the current level
for i in range(current_level_size):
current = queue.popleft()
result[-1].append(current.val)
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment