Tutorialspoint
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:

    Binary Tree Level Order Traversal with root node 3

  • 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
Binary TreePwCApple
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 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

Steps to solve by this approach:

 Step 1: Create a result list to store the level order traversal.
 Step 2: If the root is null, return an empty result.
 Step 3: Use a queue to perform breadth-first search, starting with the root node.
 Step 4: For each level, determine the number of nodes at that level (queue size).
 Step 5: Process each node at the current level, adding its value to the current level list.
 Step 6: Add the children of the current node to the queue for processing in the next level.
 Step 7: Add the completed level list to the result and continue until the queue is empty.

Submitted Code :