
Problem
Solution
Submissions
Binary Tree Level Order Traversal
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a Java program to return the level order traversal of a binary tree's node values. That is, from left to right, level by level.
Example 1
- Input:
- Output: [[3], [9, 20], [15, 7]]
- Explanation:
- Level 0 contains node with value 3.
- Level 1 contains nodes with values 9 and 20, from left to right.
- Level 2 contains nodes with values 15 and 7, from left to right.
- Combine all levels into a list of lists: [[3], [9, 20], [15, 7]].
Example 2
- Input:
- Tree: 1
- Output: [[1]]
- Explanation:
- Level 0 contains only the root node with value 1.
- There are no other levels.
- Result is [[1]].
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -1000 ≤ Node.val ≤ 1000
- Time Complexity: O(n), where n is the number of nodes in the tree
- Space Complexity: O(n), to store the result and the queue during traversal
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 breadth-first search (BFS) approach using a queue
- Process nodes level by level, starting from the root
- Keep track of the number of nodes at each level
- Add all nodes at the same level to a separate list
- Consider using two queues to differentiate between levels, or use sentinel nodes to mark level boundaries