← Back to Codes

2026-06-09 16:36:42

Binary Tree Level Order Traversal in Python and Java | LeetCode #102

Learn how to solve Binary Tree Level Order Traversal in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Binary Tree Level Order Traversal in Python and Java

In this tutorial, we will learn LeetCode #102: Binary Tree Level Order Traversal in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Binary Tree Level Order Traversal Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use breadth first search because it gives a clean and optimized solution.

Example input:
root = [8,4,12,2,6]

Expected result:
Output: [[8],[4,12],[2,6]]

Explanation:
Read tree level by level.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
root = [8,4,12,2,6]

Approach:
breadth first search

We update variables step by step until we reach:
Output: [[8],[4,12],[2,6]]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why breadth first search is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

root = [8,4,12,2,6]

We will solve it using breadth first search.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: [[8],[4,12],[2,6]]

Why?
Read tree level by level.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: [[8],[4,12],[2,6]]

Example 1

Input:
root = [8,4,12,2,6]

Output:
Output: [[8],[4,12],[2,6]]

Explanation:
Read tree level by level.

Example 2

Input:
root = [5,3,8,1,4,7,9]

Output:
[[5],[3,8],[1,4,7,9]]

Explanation:
Nodes are returned level by level.

Python Code

Here is the complete Python solution for LeetCode #102.

from collections import deque


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class TreeLevelOrderReader:
    def level_order(self, root):
        if not root:
            return []

        result = []
        queue = deque([root])

        while queue:
            level = []

            for _ in range(len(queue)):
                node = queue.popleft()
                level.append(node.val)

                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            result.append(level)

        return result


root = TreeNode(10)
root.left = TreeNode(6)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(8)
root.right.right = TreeNode(20)

reader = TreeLevelOrderReader()
print(reader.level_order(root))  # Output: [[10], [6, 15], [3, 8, 20]]

Java Code

Here is the complete Java solution for LeetCode #102.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

class TreeLevelOrderReader {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();

            for (int i = 0; i < size; 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);
            }

            result.add(level);
        }

        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(6);
        root.right = new TreeNode(15);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(8);
        root.right.right = new TreeNode(20);

        TreeLevelOrderReader reader = new TreeLevelOrderReader();
        System.out.println(reader.levelOrder(root)); // [[10], [6, 15], [3, 8, 20]]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #102: Binary Tree Level Order Traversal becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.