Binary Tree Level Order Traversal
Binary Tree Level Order Traversal is a medium trees & bst problem solved with the traversals pattern.
The best approach, bfs level by level, runs in O(n) time and O(w) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs with a depth index up.
Problem
Return the values of a binary tree level by level, from top to bottom and left to right within each level.
Examples
Example 1
- Input
root = [3, 9, 20, null, null, 15, 7]- Output
[[3], [9, 20], [15, 7]]
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to2000nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS with a depth index | O(n) | O(h) |
| BFS level by level | O(n) | O(w) |
1DFS with a depth index
O(n)O(h)Preorder DFS carrying the depth; append each value to the list for its depth.
- If depth == out.size(), add a new list.
- out.get(depth).add(val); recurse with depth + 1.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
dfs(root, 0, out);
return out;
}
private void dfs(TreeNode n, int d, List<List<Integer>> out) {
if (n == null) return;
if (d == out.size()) out.add(new ArrayList<>());
out.get(d).add(n.val);
dfs(n.left, d + 1, out);
dfs(n.right, d + 1, out);
}
}class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
out: List[List[int]] = []
self.dfs(root, 0, out)
return out
def dfs(self, n: Optional[TreeNode], d: int, out: List[List[int]]) -> None:
if n is None:
return
if d == len(out):
out.append([])
out[d].append(n.val)
self.dfs(n.left, d + 1, out)
self.dfs(n.right, d + 1, out)class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> out;
dfs(root, 0, out);
return out;
}
private:
void dfs(TreeNode* n, int d, vector<vector<int>>& out) {
if (n == nullptr) return;
if (d == (int)out.size()) out.push_back({});
out[d].push_back(n->val);
dfs(n->left, d + 1, out);
dfs(n->right, d + 1, out);
}
};function levelOrder(root) {
const out = [];
dfs(root, 0, out);
return out;
}
function dfs(n, d, out) {
if (n === null) return;
if (d === out.length) out.push([]);
out[d].push(n.val);
dfs(n.left, d + 1, out);
dfs(n.right, d + 1, out);
}2BFS level by level
O(n)O(w)The queue holds at most one level (width w).Use a queue. For each level, read size = q.size(), poll exactly that many nodes into one list and enqueue their children.
- q = [root].
- While q is not empty: size = q.size(); poll size nodes, record values, enqueue children.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
level.add(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
out.add(level);
}
return out;
}
}class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
out: List[List[int]] = []
if root is None:
return out
q = deque([root])
while q:
level = []
for _ in range(len(q)):
n = q.popleft()
level.append(n.val)
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
out.append(level)
return outclass Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> out;
if (root == nullptr) return out;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> level;
for (int i = q.size(); i > 0; i--) {
TreeNode* n = q.front(); q.pop();
level.push_back(n->val);
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
out.push_back(level);
}
return out;
}
};function levelOrder(root) {
const out = [];
if (root === null) return out;
let q = [root];
while (q.length > 0) {
const level = [];
const next = [];
for (const n of q) {
level.push(n.val);
if (n.left !== null) next.push(n.left);
if (n.right !== null) next.push(n.right);
}
q = next;
out.push(level);
}
return out;
}Edge cases to test
- Empty tree
- Unbalanced levels
Hints
Hint 1
At the start of each level, the queue holds exactly that level's nodes. Record its size before processing.
FAQ
What is the best time complexity for Binary Tree Level Order Traversal?
BFS level by level runs in O(n) time and O(w) extra space.
Which pattern does Binary Tree Level Order Traversal use?
It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Zigzag Level Order Traversal, Binary Tree Level Order Traversal II, Populating Next Right Pointers in Each Node.
Is there a brute force solution for Binary Tree Level Order Traversal?
Yes. DFS with a depth index takes O(n) time and O(h) space. Preorder DFS carrying the depth; append each value to the list for its depth.
Which edge cases should I test for Binary Tree Level Order Traversal?
Empty tree; Unbalanced levels.