LeetCode 102: Binary Tree Level Order Traversal Solution

Master LeetCode problem 102 (Binary Tree Level Order Traversal), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

102. Binary Tree Level Order Traversal

Problem Explanation

Explanation

To perform a level order traversal of a binary tree, we can use a queue data structure. We start by adding the root node to the queue. Then, we iterate through the queue as long as it is not empty. For each node popped from the queue, we add its value to the current level's list. If the node has left and right children, we add them to the queue for the next level. We continue this process until the queue is empty, ensuring that we record the values level by level.

  • Time Complexity: O(N) where N is the number of nodes in the binary tree.
  • Space Complexity: O(N) where N is the number of nodes in the binary tree.

Solution Code

import java.util.*;

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        if(root == null) {
            return levels;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        while(!queue.isEmpty()) {
            int levelSize = queue.size();
            List<Integer> level = new ArrayList<>();
            
            for(int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                
                if(node.left != null) {
                    queue.offer(node.left);
                }
                
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            
            levels.add(level);
        }
        
        return levels;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 102 (Binary Tree Level Order Traversal)?

This page provides optimized solutions for LeetCode problem 102 (Binary Tree Level Order Traversal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 102 (Binary Tree Level Order Traversal)?

The time complexity for LeetCode 102 (Binary Tree Level Order Traversal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 102 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 102 in Java, C++, or Python.

Back to LeetCode Solutions