Binary Tree Level Order Traversal
You're given the root of a binary tree. Return its values grouped level by level, from the root downward, reading each level from left to right.
Input Format
Implement levelOrder(root). Inputs below show JavaScript function arguments; there is no stdin parsing.
Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
root = [3,9,20,null,null,15,7] Output
[[3],[9,20],[15,7]] Example 2
Input
root = [] Output
[] Constraints
- 0 <= number of nodes <= 2000
- -1000 <= Node.val <= 1000
Test Cases (2)
Case 1
Args: [[3,9,20,null,null,15,7]]
Expected: [[3],[9,20],[15,7]]
Case 2
Args: [[]]
Expected: []
Topics
BFS with Queue
Process nodes level by level using a queue.
function levelOrder(root) {
if (!root) return [];
const result = [], q = [root];
let head = 0;
while (head < q.length) {
const level = [], size = q.length - head;
for (let i = 0; i < size; i++) {
const node = q[head++];
level.push(node.val);
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
result.push(level);
}
return result;
}Time: O(n) | Space: O(n)
Saved in this browser only. Private to you.