15% off all plans & roadmaps Use code
See plansBinary Tree Level Order Traversal
- LeetCode 102
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Level Order Traversal
Updated
TL;DR: Return a binary tree's values grouped by depth, left to right. Run a breadth-first search with a queue, and read the queue size at the start of each round to know how many nodes belong to the current level.
Problem
Given the root of a binary tree, return the level order traversal of its node values. That means you list the values from left to right, one level at a time, and return them as a list of lists.
Example 1
Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2
Input: root = [1] Output: [[1]]
Example 3
Input: root = [] Output: []
Constraints
- The number of nodes in the tree is in the range
[0, 2000]. -1000 <= Node.val <= 1000
Constraints that matter
- Up to 2000 nodes means even an O(n * h) solution runs in about 4 million steps, so the slow approach is correct here. It is still the wrong answer in an interview, because the linear solution is as short.
- The node count can be 0, so
rootcan be null. You must return an empty list instead of a list holding an empty list. - A tree of 2000 nodes can be a single chain of depth 2000. Recursive solutions need that much stack, which exceeds Python's default recursion limit of 1000.
- Values between -1000 and 1000 cause no overflow or precision trouble. Values are only copied, never combined, so the value range does not affect the algorithm.
Hints
Hint 1
This is a level order traversal, which is breadth-first search (BFS) on a tree.
Hint 2
Find the height h of the tree.
Solution
Intuition
This is a level order traversal, which is breadth-first search (BFS) on a tree. BFS visits every node at depth d before any node at depth d + 1. That is the order the output asks for, so the remaining job is to cut the visiting order into groups.
Picture a checkout line where each person who finishes an errand rejoins the back of the line. At the start of each round you count the people standing there, serve exactly that many, and the people who rejoin during that round form the next group.
A queue gives you the visiting order. You push the root, and every time you pop a node you push its left child and then its right child. Children always go behind everything already waiting, so nodes leave the queue in order of depth, and left to right within a depth.
The grouping comes from one observation. When a round begins, the queue holds all nodes of one level and nothing else. Read len(queue) right then and call it k. Pop exactly k nodes, and those are the whole level. The children you push during those pops wait behind them for the next round.
A second route reaches the same output without a queue. In a depth-first search you pass the depth along, and you append each node's value to the list for its depth. Left subtrees are visited before right subtrees, so each level's list fills left to right. Both routes touch each node once. The BFS version avoids deep recursion, which is why it is the one to memorise.
Worked example
Input: root = [3, 9, 20, null, null, 15, 7] Output: [[3], [9, 20], [15, 7]] Explanation: The root 3 is alone on level 0. Its children 9 and 20 form level 1, read left to right. Node 20 has children 15 and 7, which form level 2. Nodes 9, 15 and 7 are leaves, so nothing lies below level 2.
Approach 1: Brute force: one traversal per level
Find the height h of the tree. Then, for each level number from 0 to h - 1, start at the root and walk down the tree, collecting only the nodes whose depth equals that level. Each pass produces one inner list.
This is correct and needs no queue or clever bookkeeping. It is also the version a beginner writes when asked for the nodes of one level and then told to repeat it for every level.
Steps
- Compute the height of the tree with a recursive helper: 0 for null, otherwise 1 plus the larger child height.
- Create an empty result list.
- For each level from 0 up to height - 1, create an empty list for that level.
- Run a DFS from the root that tracks the current depth. When the depth equals the target level, append the node's value and stop descending. Otherwise recurse into the left child, then the right child.
- Append the level's list to the result.
- Return the result.
Dry run
The tree has height 3 (levels 0, 1, 2).
- Level 0: the DFS starts at 3 with depth 0, which matches the target. It appends 3. Result so far:
[[3]]. - Level 1: the DFS enters 3 at depth 0, which does not match. It goes left to 9 at depth 1 and appends 9. It goes right to 20 at depth 1 and appends 20. Result:
[[3],[9,20]]. - Level 2: the DFS walks 3, then 9 (children are null), then 20, then 15 and 7 at depth 2. It appends 15 and 7. Result:
[[3],[9,20],[15,7]].
The pass for level 2 visits five real nodes, the pass for level 1 visits three, and the pass for level 0 visits one. The same upper nodes are walked again for every level. The final result matches the expected output.
Complexity
| Time | O(n * h), which is O(n^2) in the worst case |
|---|---|
| Space | O(h) extra, plus the output |
Here n is the number of nodes and h is the height. Each of the h level passes can visit up to n nodes, and the height computation adds one more O(n) pass, giving O(n * h). A chain has h = n, so the worst case is O(n^2). Apart from the output, the only extra memory is the recursion stack, which is at most h frames deep.
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
sys.setrecursionlimit(10000) # a chain of 2000 nodes needs deep recursion
def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
def collect(node, depth, target, out):
if not node:
return
if depth == target:
out.append(node.val)
return
collect(node.left, depth + 1, target, out)
collect(node.right, depth + 1, target, out)
result = []
for level in range(height(root)):
out = []
collect(root, 0, level, out)
result.append(out)
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] levelOrder(TreeNode root) {
int h = height(root);
int[][] result = new int[h][];
for (int level = 0; level < h; level++) {
List<Integer> out = new ArrayList<>();
collect(root, 0, level, out);
result[level] = new int[out.size()];
for (int i = 0; i < out.size(); i++) {
result[level][i] = out.get(i);
}
}
return result;
}
private int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
private void collect(TreeNode node, int depth, int target, List<Integer> out) {
if (node == null) return;
if (depth == target) {
out.add(node.val);
return;
}
collect(node.left, depth + 1, target, out);
collect(node.right, depth + 1, target, out);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
int h = height(root);
vector<vector<int>> result;
for (int level = 0; level < h; level++) {
vector<int> out;
collect(root, 0, level, out);
result.push_back(out);
}
return result;
}
private:
int height(TreeNode* node) {
if (!node) return 0;
return 1 + max(height(node->left), height(node->right));
}
void collect(TreeNode* node, int depth, int target, vector<int>& out) {
if (!node) return;
if (depth == target) {
out.push_back(node->val);
return;
}
collect(node->left, depth + 1, target, out);
collect(node->right, depth + 1, target, out);
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const height = (node) => {
if (!node) return 0;
return 1 + Math.max(height(node.left), height(node.right));
};
const collect = (node, depth, target, out) => {
if (!node) return;
if (depth === target) {
out.push(node.val);
return;
}
collect(node.left, depth + 1, target, out);
collect(node.right, depth + 1, target, out);
};
const result = [];
const h = height(root);
for (let level = 0; level < h; level++) {
const out = [];
collect(root, 0, level, out);
result.push(out);
}
return result;
};
GoTested in our runner
func levelOrder(root *TreeNode) [][]int {
var height func(node *TreeNode) int
height = func(node *TreeNode) int {
if node == nil {
return 0
}
l, r := height(node.Left), height(node.Right)
if l > r {
return l + 1
}
return r + 1
}
var collect func(node *TreeNode, depth, target int, out *[]int)
collect = func(node *TreeNode, depth, target int, out *[]int) {
if node == nil {
return
}
if depth == target {
*out = append(*out, node.Val)
return
}
collect(node.Left, depth+1, target, out)
collect(node.Right, depth+1, target, out)
}
h := height(root)
result := make([][]int, 0, h)
for level := 0; level < h; level++ {
out := []int{}
collect(root, 0, level, &out)
result = append(result, out)
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] levelOrder(TreeNode root) {
int h = Height(root);
int[][] result = new int[h][];
for (int level = 0; level < h; level++) {
List<int> o = new List<int>();
Collect(root, 0, level, o);
result[level] = o.ToArray();
}
return result;
}
private int Height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.Max(Height(node.left), Height(node.right));
}
private void Collect(TreeNode node, int depth, int target, List<int> o) {
if (node == null) return;
if (depth == target) {
o.Add(node.val);
return;
}
Collect(node.left, depth + 1, target, o);
Collect(node.right, depth + 1, target, o);
}
}
Approach 2: DFS with a depth index
What's slow: the brute force walks the upper levels again for every deeper level, and it needs a separate height pass. Each node is reached h times in the worst case when it only needs to be handled once.
The insight that fixes it: a single DFS can carry the depth with it. When you reach a node at depth d, append its value to the list for level d, creating that list if this is the first node seen at that depth. Visit the left child before the right child, and each level's list fills in left to right order.
Steps
- Create an empty result list of lists.
- Define
dfs(node, depth). If the node is null, return. - If
depthequals the current length of the result, append a new empty list, because this is the first node found at that depth. - Append the node's value to
result[depth]. - Call
dfson the left child withdepth + 1, then on the right child withdepth + 1. - Call
dfs(root, 0)and return the result.
Dry run
Start with result = [].
dfs(3, 0): depth 0 equals the length 0, so add a new list.result = [[3]].dfs(9, 1): depth 1 equals the length 1, so add a list.result = [[3],[9]]. Both children of 9 are null and return at once.dfs(20, 1): the list for depth 1 already exists.result = [[3],[9,20]].dfs(15, 2): depth 2 equals the length 2, so add a list.result = [[3],[9,20],[15]].dfs(7, 2): the list exists, so append.result = [[3],[9,20],[15,7]].
The tree was walked once, and the output matches the expected answer.
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) for the call stack, plus the output |
Here n is the number of nodes and h is the height. Each node is passed to dfs exactly once, and each null child adds one call that returns immediately, so there are at most 2n + 1 calls and each does O(1) work. The recursion stack holds at most h frames, which is O(n) for a chain and O(log n) for a balanced tree. The output holds n values.
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
sys.setrecursionlimit(10000) # a chain of 2000 nodes needs deep recursion
result = []
def dfs(node, depth):
if not node:
return
if depth == len(result):
result.append([]) # first node seen at this depth
result[depth].append(node.val)
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 0)
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] levelOrder(TreeNode root) {
List<List<Integer>> levels = new ArrayList<>();
dfs(root, 0, levels);
int[][] result = new int[levels.size()][];
for (int i = 0; i < levels.size(); i++) {
List<Integer> level = levels.get(i);
result[i] = new int[level.size()];
for (int j = 0; j < level.size(); j++) {
result[i][j] = level.get(j);
}
}
return result;
}
private void dfs(TreeNode node, int depth, List<List<Integer>> levels) {
if (node == null) return;
if (depth == levels.size()) {
levels.add(new ArrayList<>());
}
levels.get(depth).add(node.val);
dfs(node.left, depth + 1, levels);
dfs(node.right, depth + 1, levels);
}
}
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
dfs(root, 0, result);
return result;
}
private:
void dfs(TreeNode* node, int depth, vector<vector<int>>& result) {
if (!node) return;
if (depth == (int)result.size()) {
result.push_back({});
}
result[depth].push_back(node->val);
dfs(node->left, depth + 1, result);
dfs(node->right, depth + 1, result);
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const result = [];
const dfs = (node, depth) => {
if (!node) return;
if (depth === result.length) {
result.push([]);
}
result[depth].push(node.val);
dfs(node.left, depth + 1);
dfs(node.right, depth + 1);
};
dfs(root, 0);
return result;
};
GoTested in our runner
func levelOrder(root *TreeNode) [][]int {
result := [][]int{}
var dfs func(node *TreeNode, depth int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
if depth == len(result) {
result = append(result, []int{})
}
result[depth] = append(result[depth], node.Val)
dfs(node.Left, depth+1)
dfs(node.Right, depth+1)
}
dfs(root, 0)
return result
}
C#Tested in our runner
public class Solution {
public int[][] levelOrder(TreeNode root) {
List<List<int>> levels = new List<List<int>>();
Dfs(root, 0, levels);
return levels.Select(l => l.ToArray()).ToArray();
}
private void Dfs(TreeNode node, int depth, List<List<int>> levels) {
if (node == null) return;
if (depth == levels.Count) {
levels.Add(new List<int>());
}
levels[depth].Add(node.val);
Dfs(node.left, depth + 1, levels);
Dfs(node.right, depth + 1, levels);
}
}

Solution pattern
Level Order Traversal
Approach 3: BFS with a queue and level sizeOptimalLevel Order Traversal
What's slow: the DFS is linear, but it recurses as deep as the tree and builds levels out of order, jumping between lists as it goes. A chain of 2000 nodes also overflows Python's default recursion limit. Its traversal order is not the order the problem asks for.
The insight that fixes it: breadth-first search already visits nodes level by level, so use it directly. Keep a FIFO queue. At the start of each round the queue holds exactly one level, so read its size k.
Pop k nodes into one list, pushing each node's left and right children as you go. Those children queue up behind the current level and form the next round.
Why it is correct. Claim: at the start of every round, the queue holds exactly the nodes of one depth, in left-to-right order. It holds initially, since only the root is there. Popping a level and pushing its children adds exactly the next depth behind it, so the claim holds for the next round. Because k is read before any pops, the group size is exactly that level's node count.
Steps
- If
rootis null, return an empty list. - Create a queue holding
root, and an empty result list. - While the queue is not empty, store
k = len(queue)before touching the queue. - Create an empty list
level, then repeat k times: pop the front node, append its value tolevel. - After each pop, push the node's left child if it exists, then its right child if it exists.
- After k pops, append
levelto the result. - When the queue empties, return the result.
Dry run
Each row below is one round of the outer loop, with the queue shown as it was at the start of that round.
| Round | Queue at start | k | Pops (value, children pushed) | level | result after round |
|---|---|---|---|---|---|
| 1 | [3] | 1 | 3 pushes 9, 20 | [3] | [[3]] |
| 2 | [9, 20] | 2 | 9 pushes nothing; 20 pushes 15, 7 | [9, 20] | [[3], [9, 20]] |
| 3 | [15, 7] | 2 | 15 pushes nothing; 7 pushes nothing | [15, 7] | [[3], [9, 20], [15, 7]] |
| end | [] | - | loop stops | - | [[3], [9, 20], [15, 7]] |
In round 2 the queue grows from 2 to 2 entries (9 and 20 leave, 15 and 7 arrive), yet the loop still pops exactly 2 times because k was fixed at the start. The final result is [[3],[9,20],[15,7]], the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of nodes. Every node is pushed once and popped once, and each push, pop and append costs O(1), so the total work is O(n). The queue holds at most two adjacent levels' worth of nodes at a time, and a single level can contain about n / 2 nodes in a complete tree, so the queue is O(n). The output also stores n values.
The queue never grows with the tree's depth, so a chain of 2000 nodes uses only O(1) queue space.
PythonTested in our runner
from collections import deque
from typing import List, Optional
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
if not root:
return result
queue = deque([root])
while queue:
level = []
# range(len(queue)) is evaluated once, so it fixes the level size
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] levelOrder(TreeNode root) {
List<int[]> result = new ArrayList<>();
if (root == null) {
return new int[0][];
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // fixed before any children are added
int[] level = new int[size];
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level[i] = node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(level);
}
return result.toArray(new int[0][]);
}
}
C++Tested in our runner
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root) return result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size(); // fixed before any children are added
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(level);
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const result = [];
if (!root) return result;
const queue = [root];
let head = 0; // index of the front, avoids O(n) shift calls
while (head < queue.length) {
const size = queue.length - head; // nodes in the current level
const level = [];
for (let i = 0; i < size; i++) {
const node = queue[head++];
level.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
result.push(level);
}
return result;
};
GoTested in our runner
func levelOrder(root *TreeNode) [][]int {
result := [][]int{}
if root == nil {
return result
}
queue := []*TreeNode{root}
for len(queue) > 0 {
size := len(queue) // fixed before any children are added
level := make([]int, 0, size)
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
level = append(level, node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
result = append(result, level)
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] levelOrder(TreeNode root) {
List<int[]> result = new List<int[]>();
if (root == null) {
return new int[0][];
}
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0) {
int size = queue.Count; // fixed before any children are added
int[] level = new int[size];
for (int i = 0; i < size; i++) {
TreeNode node = queue.Dequeue();
level[i] = node.val;
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
result.Add(level);
}
return result.ToArray();
}
}
Common mistakes
- Writing the inner loop as
while i < queue.size()in Java or C++. The size grows as you push children, so levels merge. Storesize = queue.size()in a variable before the inner loop. - Pushing null children, as in
queue.offer(node.left)with no check. The next pop returns null andnode.valthrows. Guard each push withif (node.left != null). - Skipping the empty-tree check. With
root = null,queue.offer(root)puts a null in the queue, and the first pop crashes. Return an empty list before building the queue. - Using
list.pop(0)as the queue in Python. Each call shifts the whole list, which costs O(n). Usecollections.dequeandpopleft(). - In the DFS version, appending to
result[depth]before checkingdepth == len(result). The first node at a new depth raises an index error. Create the empty list first when depth equals the length. - Reusing one
levellist across rounds, for example callinglevel.clear()afterresult.append(level)in a language that stores references. Every stored level ends up empty. Create a fresh list each round.
Edge cases
root = [](null root): return[], not[[]].- A single node
[1]: return[[1]], one round with k = 1. - A left-only chain of 2000 nodes: output is 2000 lists of one value each. The BFS queue stays at size 1, but the recursive approaches need a stack 2000 deep.
- A right-only chain: each level holds one node, and the traversal must still push the right child when the left is null.
- A complete tree such as 7 nodes in 3 levels: output sizes 1, 2, 4. The queue peaks at 4 entries, which shows the O(n) space.
- Duplicate and negative values such as
[-1, -1, -1]: the traversal uses nodes, not values, so duplicates change nothing. Expected[[-1],[-1,-1]].
Follow-ups interviewers ask
- How would you return the levels from the bottom up, as in Binary Tree Level Order Traversal II?
- Run the same BFS, then reverse the list of levels at the end. That is O(n) extra and keeps each level's left to right order. You can also insert each new level at the front of a deque, which avoids the final reversal.
- How do you get a zigzag order, where odd levels go right to left?
- Keep the BFS as is and track the level index. When the index is odd, reverse that level's list before appending it, or fill a preallocated array from the back. The queue order must stay left to right, because the children of the next level depend on it.
- Can you do it in O(1) extra space beyond the output?
- Not with the standard queue, since a complete tree's widest level is about n / 2 nodes. Recursive DFS needs O(h) stack and is O(log n) on a balanced tree, but O(n) on a chain. If nodes had parent pointers you could walk level by level with no queue, but the input tree does not give them. Constant space in general would require modifying the tree, such as a Morris-style threaded traversal, which is far more complex than it is worth here.
Binary Tree Level Order Traversal FAQ
What is the time complexity of Binary Tree Level Order Traversal?
The BFS and DFS solutions are both O(n), where n is the number of nodes, because every node is handled once with constant work. The brute force that traverses once per level is O(n * h), which is O(n^2) on a chain.
Why use a queue for Binary Tree Level Order Traversal?
A queue is first in, first out, so children wait behind every node already queued. That keeps nodes in depth order. Reading the queue size at the start of each round then tells you where the current level ends.
What is the space complexity of the BFS solution?
It is O(n). The queue holds at most about one level at a time, and a complete tree's bottom level has roughly n / 2 nodes. The output also stores all n values.
Can Binary Tree Level Order Traversal be solved with recursion?
Yes. Pass the depth into a DFS, create a new list when the depth first appears, and append the node's value to that depth's list. Visit left before right and the order inside each level is correct. In Python, raise the recursion limit, because a 2000-node chain exceeds the default of 1000.
Can Binary Tree Level Order Traversal be solved in O(1) extra space?
Not in a useful way. Level order needs to remember the pending nodes of a level, and that can be about n / 2 nodes. The recursive version trades that for stack depth, which is also O(n) on a chain.
Why store the queue size before the inner loop in LeetCode 102?
Pushing children changes the queue length during the loop. If the loop condition reads the live size, it keeps going into the next level and merges the two. A fixed k stops the round after exactly one level.
Asked at
See which companies ask this — Pro
Related problems
- Binary Tree Right Side View · same technique: Level Order Traversal
- Binary Tree Zigzag Level Order Traversal · same technique: Level Order Traversal
- Find Largest Value in Each Tree Row · same technique: Level Order Traversal
- Maximum Level Sum of a Binary Tree · same technique: Level Order Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Kth Smallest Element in a BST · same pattern: Tree Traversal Patterns (DFS & BFS)
- Count Good Nodes in Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)