
Problem
Solution
Submissions
Binary Tree Level Order Traversal
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to perform level order traversal of a binary tree. Given the root of a binary tree, return the level order traversal of its nodes' values as a 2D array where each sub-array represents one level of the tree.
Example 1
- Input: root = [3,9,20,null,null,15,7]
- Output: [[3],[9,20],[15,7]]
- Explanation:
- The root node 3 is at level 0.
- Nodes 9 and 20 are at level 1, children of node 3.
- Nodes 15 and 7 are at level 2, children of node 20.
- Each level is collected into separate arrays: [3], [9,20], [15,7].
- The root node 3 is at level 0.
Example 2
- Input: root = [1]
- Output: [[1]]
- Explanation:
- The tree contains only the root node.
- Node 1 is at level 0.
- The result contains one level with one element: [1].
- Final output is [[1]].
- The tree contains only the root node.
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -1000 ≤ Node.val ≤ 1000
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a queue data structure to implement breadth-first search (BFS)
- Start by adding the root node to the queue
- For each level, process all nodes currently in the queue
- Add children of current level nodes to the queue for the next level
- Store each level's values in a separate array