Problem
Given the root of a binary tree, return its node values level by level (left to right).
Example
Input: [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Solution
BFS with a queue. Process all nodes at the current level before moving to the next.
from collections import deque
def level_order(root):
if not root: return []
result = []
q = deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
result.append(level)
return result
function levelOrder(root) {
if (!root) return [];
const result = [];
const q = [root];
while (q.length) {
const level = [];
const size = q.length;
for (let i = 0; i < size; i++) {
const node = q.shift();
level.push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
result.push(level);
}
return result;
}
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();
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;
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
result.add(level);
}
return result;
}
Complexity
- Time: O(n)
- Space: O(n)
Explanation
Capturing queue size at the start of each level lets us process exactly that level’s nodes before adding the next level.
Comments
Join the discussion. Got a question, found an issue, or want to share your experience?