Tutorialspoint
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]].
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]].
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
Binary TreeGoogleWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize a queue and add the root node to it.
 Step 2: Create result array to store level-wise traversal.
 Step 3: While queue is not empty, get the current level size.
 Step 4: Process all nodes at the current level by dequeuing them.
 Step 5: Store the values of current level nodes in the result array.
 Step 6: Add the children of processed nodes to the queue for next level.
 Step 7: Increment the level count and repeat until queue is empty.

Submitted Code :