MediumNo. 0102

Binary Tree Level Order Traversal — LeetCode 102 Python Solution

Topics
Tree, Breadth-First Search, Binary Tree
Reading time
4 min

The problem

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example

Input
root = [3,9,20,null,null,15,7]
Output
[[3],[9,20],[15,7]]

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ans = []
        if root is None:
            return ans
        q = deque([root])
        while q:
            t = []
            for _ in range(len(q)):
                node = q.popleft()
                t.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            ans.append(t)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 102. Binary Tree Level Order Traversal is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 102. Binary Tree Level Order Traversal?

LeetCode 102. Binary Tree Level Order Traversal is rated Medium on LeetCode.

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

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 102. Binary Tree Level Order Traversal?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 102. Binary Tree Level Order Traversal cover?

LeetCode 102. Binary Tree Level Order Traversal is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.