ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Simple BFS Level Order Traversal

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1from collections import deque
2
3class TreeNode:
4def __init__(self, val=0, left=None, right=None):
5self.val = val
6self.left = left
7self.right = right
8
9def levelOrder(root: TreeNode | None) -> list[list[int]]:
10if not root:
11return []
12
13result = []
14queue = deque([root])
15
16while queue:
17level_size = len(queue)
18current_level = []
19
20for _ in range(level_size):
21node = queue.popleft()
22current_level.append(node.val)
23
24if node.left:
25queue.append(node.left)
26if node.right:
27queue.append(node.right)
28result.append(current_level)
29
30return result
Algorithm description viewbox

Simple BFS Level Order Traversal

Algorithm description:

This function performs a level order traversal (also known as Breadth-First Search or BFS) on a binary tree. It visits nodes level by level, from left to right. This is commonly used to visualize tree structures or find the shortest path in an unweighted graph represented as a tree.

Algorithm explanation:

The algorithm uses a queue to manage nodes to visit. It starts by adding the root to the queue. In each iteration of the main loop, it processes all nodes at the current level. The size of the queue at the beginning of the loop determines how many nodes are on the current level. For each node dequeued, its value is added to the current level's list, and its children (if they exist) are enqueued for the next level. This ensures nodes are visited in a breadth-first manner. Time complexity is O(N) where N is the number of nodes, as each node is visited and processed once. Space complexity is O(W) where W is the maximum width of the tree, for the queue, which in the worst case (a complete binary tree) can be O(N).

Pseudocode:

function levelOrder(root):
  if root is null:
    return empty list

  result = empty list
  queue = new queue
  add root to queue

  while queue is not empty:
    level_size = size of queue
    current_level_nodes = empty list

    for i from 0 to level_size - 1:
      node = dequeue from queue
      add node.value to current_level_nodes

      if node has left child:
        enqueue node.left
      if node has right child:
        enqueue node.right
    add current_level_nodes to result

  return result