LeetCode solutions

102. Binary Tree Level Order Traversal

My accepted JavaScript and Python solution to LeetCode problem 102, Binary Tree Level Order Traversal, running in 1ms.

  • Difficulty: Medium
  • JavaScript
  • Python
  • Runtime 1ms
  • Memory 59.3MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 1ms, memory 59.3MB, accepted 2025-12-24.

javascript
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if (!root) return [];
    
    const result = [];
    const queue = [root];
    
    while (queue.length > 0) {
        const levelSize = queue.length;
        const level = [];
        
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift();
            level.push(node.val);
            
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
        
        result.push(level);
    }
    
    return result;
};

Python

Accepted on LeetCode — runtime 4ms, memory 13.1MB, accepted 2025-12-24.

python
class Solution:
    def levelOrder(self, root):
        if not root:
            return []
        result, queue = [], [root]
        while queue:
            level = []
            for _ in range(len(queue)):
                node = queue.pop(0)
                level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(level)
        return result

Source