LeetCode solutions

107. Binary Tree Level Order Traversal II

My accepted JavaScript solution to LeetCode problem 107, Binary Tree Level Order Traversal II, running in 0ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 0ms
  • Memory 57.8MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 0ms, memory 57.8MB, accepted 2025-12-24.

javascript
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = 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.unshift(level);  // Add to front instead of end
    }
    
    return result;
};

Source