Coding Pattern:

Tree Breadth First Search

This pattern has an earnable cheat sheet.

Note

Familiarize yourself with the tree and deque data structures before proceeding past this section.

Pattern concept

Step 1 of 33
Tree Breadth First Search Slide 1: Tree breadth first search:...
Tree Breadth First Search Slide 2: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 3: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 4: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 5: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 6: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 7: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 8: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 9: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 10: Here's a side-by-side walkthrough.
Tree Breadth First Search Slide 11: This section will focus on BFS for trees.
Tree Breadth First Search Slide 12: To traverse through the tree level by level, we use a queue to track the nodes we w... our queue queue = deque([5])
Tree Breadth First Search Slide 13: queue.append(9) A queue works the same way as in real life, the first item in is the first item out...
Tree Breadth First Search Slide 14: queue.append(3) A queue works the same way as in real life, the first item in is the first item out...
Tree Breadth First Search Slide 15: queue.popleft() A queue works the same way as in real life, the first item in is the first item out...
Tree Breadth First Search Slide 16: queue.popleft() A queue works the same way as in real life, the first item in is the first item out...
Tree Breadth First Search Slide 17: queue.popleft() A queue works the same way as in real life, the first item in is the first item out...
Tree Breadth First Search Slide 18: result: [[1], [2, 3], [4]] Consider this example:...
Tree Breadth First Search Slide 19: result: [] Start the queue with the root node, where the queue tracks nodes we'll explore. Ini...
Tree Breadth First Search Slide 20: result: [] Initialize an empty list for the new level. Take a snapshot of the queue and iterat... iterations: 0/1 level: []
Tree Breadth First Search Slide 21: result: [] Pop off the next node on the queue, and append its value to level. iterations: 1/1 level: [1]
Tree Breadth First Search Slide 22: result: [] Append its left child (if it exists) to the queue. iterations: 1/1 level: [1]
Tree Breadth First Search Slide 23: result: [] Append its right child (if it exists) to the queue. iterations: 1/1 level: [1]
Tree Breadth First Search Slide 24: result: [[1]] After we've finished iterating through the snapshot of the queue, append level to r... level: [1]
Tree Breadth First Search Slide 25: result: [[1]] Move onto traversing the next level. Initialize a new list to use for level. Take a... level: [] iterations: 0/2
Tree Breadth First Search Slide 26: result: [[1]] Pop off the next node from the queue and append its value to level. level: [2] iterations: 1/2
Tree Breadth First Search Slide 27: result: [[1]] Append the node's left child (if it exists) to the queue. Append its right child (i... level: [2] iterations: 1/2
Tree Breadth First Search Slide 28: result: [[1]] Pop off the queue and append the node's value to level. Append any child nodes to t... level: [2, 3] iterations: 2/2
Tree Breadth First Search Slide 29: result: [[1], [2, 3]] We've finished iterating through the snapshot of the queue, so append level to resu... level: [2, 3]
Tree Breadth First Search Slide 30: result: [[1], [2, 3]] Move onto the next level. Initialize a new list for level. Take a snapshot of the q... level: [] iterations: 0/1
Tree Breadth First Search Slide 31: result: [[1], [2, 3]] Pop off a node from the queue and append its value to level. Append any child nodes... level: [4] iterations: 1/1
Tree Breadth First Search Slide 32: result: [[1], [2, 3], [4]] After iterating through the queue, append list to result. level: [4]
Tree Breadth First Search Slide 33: result: [[1], [2, 3], [4]] Once the queue is empty, we've finished traversing through the tree. Return result.

Use ← → arrow keys

Code snippets

# Definition for a TreeNode.
class TreeNode:
   def __init__(self, val=0, left=None, right=None):
     self.val = val
     self.left = left
     self.right = right

# Return a list of list of nodes in the tree, organized by levels.
def level_order_traversal(root: TreeNode) -> List[str]:
  # Initialize a queue with the starting node.
  queue = deque([root])
  result = []

  while queue:
    level = []  # Track the current level's values.

    # Iterate through the queue's initial length.
    for _ in range(len(queue)):
      node = queue.popleft()  # Pop off the queue.

      # Save the current node value for this problem.
      level.append(node.val)

      # Add the child nodes to the queue.
      if node.left:
        queue.append(node.left)
      if node.right:
        queue.append(node.right)
    
    result.append(level)

  return result

How to identify

Does the problem involve any of these?

Note

BFS usually takes O(n) to traverse the tree, and O(w) space where w is the widest level of the tree.