KatInterview

102. Binary Tree Level Order Traversal

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a level-order traversal of a binary tree. This means we need to visit all nodes at the same depth (or level) from left to right, before moving on to the nodes at the next level. The output should be a list of lists, where each inner list contains the values of nodes at one level.

Solution

Binary Tree Level Order Traversal in Python

# 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
from collections import deque

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        # Handle the edge case of an empty tree
        if not root:
            return []
        
        result = []
        # Create a queue for BFS, using deque for efficient appends and poplefts
        queue = deque([root])
        
        # Process nodes level by level
        while queue:
            # Get the number of nodes at the current level
            level_size = len(queue)
            current_level = []
            
            # Process all nodes for the current level
            for _ in range(level_size):
                # Dequeue the node from the left
                node = queue.popleft()
                current_level.append(node.val)
                
                # Add children to the queue for the next level
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
            # Add the completed level to the result
            result.append(current_level)
            
        return result

Binary Tree Level Order Traversal in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        // Handle the edge case of an empty tree
        if (root == null) {
            return result;
        }
        
        // Create a queue for BFS and add the root
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        
        // Process nodes level by level
        while (!queue.isEmpty()) {
            // Get the number of nodes at the current level
            int levelSize = queue.size();
            List<Integer> currentLevel = new ArrayList<>();
            
            // Process all nodes for the current level
            for (int i = 0; i < levelSize; i++) {
                TreeNode currentNode = queue.poll();
                currentLevel.add(currentNode.val);
                
                // Add children to the queue for the next level
                if (currentNode.left != null) {
                    queue.offer(currentNode.left);
                }
                if (currentNode.right != null) {
                    queue.offer(currentNode.right);
                }
            }
            // Add the completed level to the result
            result.add(currentLevel);
        }
        
        return result;
    }
}

Binary Tree Level Order Traversal in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        // Handle the edge case of an empty tree
        if (root == nullptr) {
            return result;
        }
        
        // Create a queue for BFS and add the root
        queue<TreeNode*> q;
        q.push(root);
        
        // Process nodes level by level
        while (!q.empty()) {
            // Get the number of nodes at the current level
            int levelSize = q.size();
            vector<int> currentLevel;
            
            // Process all nodes for the current level
            for (int i = 0; i < levelSize; ++i) {
                TreeNode* node = q.front();
                q.pop();
                currentLevel.push_back(node->val);
                
                // Add children to the queue for the next level
                if (node->left != nullptr) {
                    q.push(node->left);
                }
                if (node->right != nullptr) {
                    q.push(node->right);
                }
            }
            // Add the completed level to the result
            result.push_back(currentLevel);
        }
        
        return result;
    }
};

Binary Tree Level Order Traversal in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[][] {
    // Handle the edge case of an empty tree
    if (!root) {
        return [];
    }

    const result: number[][] = [];
    // Create a queue for BFS. A simple array with push/shift works.
    const queue: TreeNode[] = [root];

    // Process nodes level by level
    while (queue.length > 0) {
        // Get the number of nodes at the current level
        const levelSize = queue.length;
        const currentLevel: number[] = [];

        // Process all nodes for the current level
        for (let i = 0; i < levelSize; i++) {
            // Dequeue the node. shift() removes the first element.
            const node = queue.shift()!;
            currentLevel.push(node.val);

            // Enqueue children for the next level
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        // Add the completed level to the result
        result.push(currentLevel);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.