Introduction
Imagine you want to visit every node in a tree starting from the top and moving level by level downwards. The challenge is to visit nodes in the order they appear by levels, not by depth or branches.
Jump into concepts and practice - no test required
Imagine a group of people standing in rows for a photo. The photographer takes pictures row by row, starting from the front row and moving backward. Everyone in the front row is captured before moving to the next row behind.
┌─────┐
│Root │
└──┬──┘
│
┌───────┴───────┐
│ │
┌──┴──┐ ┌──┴──┐
│Left │ │Right│
└──┬──┘ └──┬──┘
│ │
┌─┴─┐ ┌─┴─┐
│L1 │ │R1 │
└───┘ └───┘
Traversal order:
Root → Left → Right → L1 → R1from collections import deque class Node: def __init__(self, value): self.value = value self.left = None self.right = None def level_order_traversal(root): if not root: return [] result = [] queue = deque([root]) while queue: node = queue.popleft() result.append(node.value) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result # Example tree: # 1 # / \ # 2 3 # / \ \ # 4 5 6 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) print(level_order_traversal(root))
level-order traversal (BFS) of a binary tree?n into a queue named q in Python during level-order traversal?append() adds elements to the end.q.append(n) correctly adds node n to the queue's rear.1 / \ 2 3 / / \ 4 5 6
queue = [root]
while queue:
node = queue.pop()
print(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)