Ten problems that drill the breadth-first search / level-order pattern from Lesson 12. Open a problem, try it yourself first, then read how to reach the solution. Each solution here was actually run and tested.
How to practise. Memorise the level-by-level skeleton —
q = deque([root]), thenwhile q:with an innerfor _ in range(len(q)):so you peel off exactly one level per outer step. Once that’s muscle memory, most of these differ only in what you record per level. Notice that Rotting Oranges and Word Ladder are the same BFS on a grid and on a word graph — BFS gives shortest paths when every step costs the same.
Binary-tree problems use this node (LeetCode’s TreeNode); BFS uses deque:
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rightThe 10 problems
- 1Average of Levels in Binary Tree (LeetCode 637)EasyReturn the mean value of each level of a binary tree: BFS one level at a time, summing as you go.arrow_forward
- 2Minimum Depth of Binary Tree (LeetCode 111)EasyFind the depth of the shallowest leaf: BFS meets leaves in depth order, so the first leaf popped wins.arrow_forward
- 3Cousins in Binary Tree (LeetCode 993)EasyDecide if two nodes are cousins (same depth, different parents) by recording each one's parent and depth.arrow_forward
- 4Binary Tree Level Order Traversal (LeetCode 102)MediumReturn a tree's values grouped by level: the canonical BFS loop with a queue-size snapshot per level.arrow_forward
- 5Binary Tree Level Order Traversal II (LeetCode 107)MediumReturn a tree's levels from the bottom up: run the normal level-order BFS, then reverse the list of levels.arrow_forward
- 6Binary Tree Right Side View (LeetCode 199)MediumList the nodes you'd see looking at a tree from the right: BFS by level and keep each level's last node.arrow_forward
- 7Binary Tree Zigzag Level Order Traversal (LeetCode 103)MediumReturn tree levels alternating left-to-right and right-to-left: normal BFS, but fill each level via a deque.arrow_forward
- 8Populating Next Right Pointers in Each Node (LeetCode 116)MediumLink each node to its right neighbour in a perfect tree, using the level above's next pointers as the queue.arrow_forward
- 9Rotting Oranges (LeetCode 994)MediumMinutes until every orange rots: multi-source BFS from all rotten oranges at once, one level per minute.arrow_forward
- 10Word Ladder (LeetCode 127)HardShortest chain of one-letter edits from begin to end: BFS over words, generating neighbours letter by letter.arrow_forward