Level Order Traversal of Binary Tree

Return node values grouped per depth using a queue-based BFS.

Medium
Time O(n) Space O(n)
LeetCode
3 min read
tree bfs queue

Problem#

Given the root of a binary tree, return its level-order traversal: a list of lists where each inner list contains the values at one depth, left to right.

Examples#

  • [3,9,20,null,null,15,7][[3],[9,20],[15,7]]
  • [1][[1]]
  • [][]

Constraints#

  • 0 <= n <= 2000, -1000 <= Node.val <= 1000.

Hints#

Hint 1
A queue gives breadth-first order naturally — but you need to know where each level ends.
Hint 2
Snapshot the queue size at the start of each level; that many pops belong to this depth.

Approach#

Push the root, then repeatedly drain exactly queue.size() nodes before moving to the next level — that snapshot delimits the boundary without sentinels.

Solution#

Level Order Traversal of Binary Tree
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
vector<int> level;
level.reserve(sz);
for (int i = 0; i < sz; ++i) {
TreeNode* cur = q.front(); q.pop();
level.push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
ans.push_back(std::move(level));
}
return ans;
}
};

Editorial#

Capturing the queue size before the inner loop is the trick: any node enqueued during the iteration belongs to the next level and is excluded by the fixed bound. This avoids depth tags or null sentinels.

Complexity#

  • Time: O(n) — every node enqueued/dequeued once.
  • Space: O(n) for the queue and output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.