107. Binary Tree Level Order Traversal II
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 requires us to perform a level-order traversal on a given binary tree. However, unlike the standard level-order traversal which is top-down (root to leaves), this one needs to be bottom-up (leaves to root). For each level, the nodes should be read from left to right.
Solution
Binary Tree Level Order Traversal II 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 levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
# Handle the edge case of an empty tree
if not root:
return []
# Use collections.deque for an efficient queue implementation in BFS
queue = deque([root])
# Use collections.deque for the result list to efficiently prepend levels (O(1) time)
result = deque()
while queue:
level_size = len(queue)
current_level = []
# Process all nodes at the current level
for _ in range(level_size):
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)
# Prepend the current level to the result deque.
# This builds the list in reverse (bottom-up) order directly.
result.appendleft(current_level)
# Convert the deque to a list before returning
return list(result)
Binary Tree Level Order Traversal II 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>> levelOrderBottom(TreeNode root) {
// Use a LinkedList to store the result. This allows efficient prepending (addFirst or add(0, ...)),
// which builds the bottom-up order directly without a final reversal step.
LinkedList<List<Integer>> result = new LinkedList<>();
if (root == null) {
return result; // Return empty list for an empty tree
}
// Queue for Breadth-First Search (BFS)
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size(); // Number of nodes at the current level
List<Integer> currentLevel = new ArrayList<>();
// Process all nodes at the current level
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
// Add children to the queue for the next level
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
// Prepend the current level's list to the result.
// This builds the list in reverse (bottom-up) order.
result.add(0, currentLevel);
}
return result;
}
}
Binary Tree Level Order Traversal II 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
if (!root) {
return result; // Return empty list for empty tree
}
// Use a queue for Breadth-First Search (BFS)
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int levelSize = q.size(); // Number of nodes at the current level
vector<int> currentLevel;
// Process all nodes at 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) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
// Add the current level's values to the result
result.push_back(currentLevel);
}
// The result is currently top-down, reverse it to get bottom-up
reverse(result.begin(), result.end());
return result;
}
};
Binary Tree Level Order Traversal II 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 levelOrderBottom(root: TreeNode | null): number[][] {
const result: number[][] = [];
// Handle the edge case of an empty tree
if (!root) {
return result;
}
// Use a simple array as a queue for BFS
const queue: TreeNode[] = [root];
while (queue.length > 0) {
const levelSize = queue.length; // Number of nodes at the current level
const currentLevel: number[] = [];
// Process all nodes at the current level
for (let i = 0; i < levelSize; i++) {
// 'shift()' removes the first element and is O(N), but acceptable here.
const node = queue.shift()!; // Non-null assertion as we know queue is not empty
currentLevel.push(node.val);
// Add children to the queue for the next level
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
// Prepend the current level's list to the result using unshift().
// This builds the list in reverse (bottom-up) order directly.
// Note: unshift() can be less performant than push() on large arrays.
result.unshift(currentLevel);
}
return result;
};
More Medium LeetCode answers
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.