
Problem
Solution
Submissions
Binary Tree Level Order Traversal
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to perform level order traversal of a binary tree. Level order traversal visits all nodes at the current depth before moving to nodes at the next depth level. Return the result as a 2D array where each sub-array contains the values of nodes at each level.
Example 1
- Input: Tree structure [3,9,20,null,null,15,7]
- Output: [[3],[9,20],[15,7]]
- Explanation:
- Level 0 contains only the root node 3.
- Level 1 contains nodes 9 and 20.
- Level 2 contains nodes 15 and 7.
- Therefore, level order traversal is [[3],[9,20],[15,7]].
- Level 0 contains only the root node 3.
Example 2
- Input: Tree structure [1]
- Output: [[1]]
- Explanation:
- The tree has only one node at level 0.
- Level 0 contains only the root node 1.
- Therefore, level order traversal is [[1]].
- The tree has only one node at level 0.
Constraints
- The number of nodes in the tree is in the range [0, 2000]
- -1000 ≤ Node.val ≤ 1000
- You must traverse level by level from left to right
- Time Complexity: O(n)
- Space Complexity: O(w) where w is the maximum width of the tree
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 level order traversal
- Start by adding the root node to the queue
- For each level, process all nodes currently in the queue
- Add the children of processed nodes to the queue for the next level
- Keep track of the number of nodes at each level
- Store the values of nodes at each level in separate arrays