all entries
A-053Day 532026.06.29mediumleetcode #102neetcode150

Binary Tree Level Order Traversal

#tree#breadth-first-search#binary-tree
leetcode #102 · binary-tree-level-order-traversal
01

Problem

· problem
P.053

Binary Tree Level Order Traversal

leetcode #102

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

constraints
  • · 0 ≤ number of nodes ≤ 2000
  • · -1000 ≤ Node.val ≤ 1000
// paraphrased summary — see source for full text
examples
example 1input → output
[3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]
example 2input → output
[1]
[[1]]
example 3input → output
[]
[]
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • What does "level order traversal" mean exactly?
  • Should nodes within each level be ordered left-to-right?
  • What should we return for an empty tree?
  • Can node values be negative?
  • Should we return nodes in a single flattened list?
  • Would depth-first search be a better approach?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize result list
res = []
res = [[]]
res = None
step 2· Initialize queue
q = collections.deque()
q = []
q = Stack()
step 3· Seed queue with root
q.append(root)
q.append(root.val)
res.append([root.val])
step 4· Process while queue has nodes
while q:
while q is not None:
while len(q) > 0:
step 5· Process exactly current level's nodesnested
for i in range(len(q)):
for node in q:
for i in range(len(q) - 1):
step 6· Dequeue and record node value│ │ nested
node = q.popleft()
node = q.pop()
node = q[0]
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
# Definition for a binary tree node.
2
# class TreeNode:
3
#     def __init__(self, x):
4
#         self.val = x
5
#         self.left = None
6
#         self.right = None
7
8
9
class Solution:
10
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
11
        res = []
12
        q = collections.deque()
13
        if root:
14
            q.append(root)
15
16
        while q:
17
            val = []
18
19
            for i in range(len(q)):
20
                node = q.popleft()
21
                val.append(node.val)
22
                if node.left:
23
                    q.append(node.left)
24
                if node.right:
25
                    q.append(node.right)
26
            res.append(val)
27
        return res
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[3,9,20,null,null,15,7]
[[3],[9,20],[15,7]]
case 2
[1]
[[1]]
case 3
[]
[]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.