Skip to main content

Binary Tree Level Order Traversal II

LeetCode 107 | Difficulty: Medium​

Medium

Problem Description​

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

Example 1:

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

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

- The number of nodes in the tree is in the range `[0, 2000]`.

- `-1000 <= Node.val <= 1000`

Topics: Tree, Breadth-First Search, Binary Tree


Approach​

Tree BFS (Level-Order)​

Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 308 ms)​

MetricValue
Runtime308 ms
MemoryN/A
Date2018-07-13
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<IList<int>> LevelOrderBottom(TreeNode root) {
Queue<TreeNode> level = new Queue<TreeNode>();
IList<IList<int>> result = new List<IList<int>>();
if (root == null) return result;
level.Enqueue(root);
while (level.Count != 0)
{
int rowCount = level.Count;
List<int> row = new List<int>();
for (int i = 0; i < rowCount; i++)
{
var front = level.Dequeue();
if (front.left != null) level.Enqueue(front.left);
if (front.right != null) level.Enqueue(front.right);
row.Add(front.val);
}
result.Add(row);
}
return result.Reverse().ToList();
}
}

Complexity Analysis​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Consider: "What information do I need from each subtree?" β€” this defines your recursive return value.