Tutorialspoint
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].
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]].
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)
QueueAppleD. E. Shaw
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 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

Steps to solve by this approach:

  Step 1: Handle the edge case where the root is null by returning an empty array.

 Step 2: Initialize a result array to store levels and a queue with the root node for BFS traversal.
 Step 3: Continue processing while the queue contains nodes to visit.
 Step 4: Record the current queue size to know how many nodes belong to the current level.
 Step 5: Process all nodes in the current level by dequeuing them and adding their values to the current level array.
 Step 6: Add the left and right children of each processed node to the queue for the next level.
 Step 7: Add the completed current level array to the result and repeat until all levels are processed.

Submitted Code :