You get the root of a binary tree. Return its values level by level: first the root, then the nodes one edge below it, then the next level, each level from left to right, as a list of lists.
Example: a root 5 with children 2 and 9, where 2 has a left child 1 and 9 has children 7 and 11, gives [[5], [2, 9], [1, 7, 11]].
Try it yourself first: LeetCode 102 ↗. Then step through the solution below.
Find each node's depth with any traversal, then sort the values by depth, keeping left-to-right order inside a level: O(n log n). A depth-first search does better: it carries each node's depth down and adds the value to levels[depth] as it goes, in one pass, O(n), each level still filling left to right.
The clue is in the words "level by level": the nodes nearest the root first, which is the order a queue gives. A queue hands nodes out in the order they went in. If each node, when it is taken out, puts its children in, the nodes come out level by level, left to right: this is breadth-first search on a tree.
To know where one level ends, read the queue's length before taking anything out and keep it as size: at that moment the queue holds exactly the next level, and its children all go in behind it. Take size nodes, and the level is complete.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def level_order(root): if root is None: return [] levels = [] queue = deque([root]) while queue: level = [] size = len(queue) for _ in range(size): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) levels.append(level) return levels
Now write it yourself on LeetCode 102 ↗, or go on: Number of Islands →
levels starts empty. It will hold the values of each level, one list per level.level starts empty.size is 1: the queue holds exactly this level, so the loop takes 1 node.node.level.size nodes are taken: the level is complete. Add [5] to levels.level starts empty.size is 2: the queue holds exactly this level, so the loop takes 2 nodes.level.level.size nodes are taken: the level is complete. Add [2, 9] to levels.level starts empty.size is 3: the queue holds exactly this level, so the loop takes 3 nodes.level. It has no children.level. It has no children.level. It has no children.size nodes are taken: the level is complete. Add [1, 7, 11] to levels.Note
The queue in Python is collections.deque: popleft is O(1). A plain list's pop(0) moves every other element one place, O(n), which on a wide tree turns the whole traversal into O(n2). Java uses ArrayDeque, with offer and poll; C++ uses std::queue. Both must read the size before the loop, as size here: a loop that tests i < queue.size() reads it again after the children went in, and two levels run together.
| Approach | Time | Space |
|---|---|---|
| Brute force: the depth of every node, then a sort by depth | O(n log n) | O(n) |
| Depth-first search, passing the depth down | O(n) | O(n) |
| Queue, level by level this page | O(n) | O(n) |
[[5]].[[3], [2], [1]].The blocks below are steps of Binary Tree Level Order Traversal in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example tree and on an empty tree, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.
Your algorithm
Blocks
Now write it yourself on LeetCode 102 ↗, or go on: Number of Islands →
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def level_order(root): if root is None: return [] levels = [] queue = deque([root]) while queue: level = [] size = len(queue) for _ in range(size): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) levels.append(level) return levelsWhat about zigzag order? Odd levels left to right, even levels right to left: run exactly the same loop and reverse every second level before adding it (or fill it from the other end with a deque). Still O(n) time and space. This is Binary Tree Zigzag Level Order Traversal (LeetCode 103).
Note
The same loop answers other problems by keeping one value per level: the last value of each level gives the tree's right side view (LeetCode 199), the average of each level's values gives the level averages (LeetCode 637), and stopping at the first level that has a leaf gives the minimum depth (LeetCode 111).
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.