Skip to content

Instantly share code, notes, and snippets.

@jonathanagustin
Created July 21, 2020 04:14
Show Gist options
  • Select an option

  • Save jonathanagustin/f984b2baa9ef583420e7116c5be12ca7 to your computer and use it in GitHub Desktop.

Select an option

Save jonathanagustin/f984b2baa9ef583420e7116c5be12ca7 to your computer and use it in GitHub Desktop.
Basic Iterative BFS
# 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 levelOrder(self, root: TreeNode) -> List[List[int]]:
levels = []
if not root:
return levels
q = collections.deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
levels.append(level)
return levels
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment