Leetcode Binary Tree Level Order Traversal II Java Solution
// SOLVING THIS WITH AN AI ASSISTANT (2026)
If you are working through this problem with an AI coding assistant — Claude, ChatGPT, Cursor chat, Gemini, GitHub Copilot, Aider, or any agent — the goal isn’t to ask for the answer. It is to use the tool to understand the pattern. The prompt sequence I’d run:
- Spec it back to me first. “In your own words, what is this problem actually testing? What’s the smallest example that fails the naive approach?”
- Brute-force first, optimize after. “Write the simplest correct solution, even if it’s O(n²). Don’t optimize. Just make it correct, with comments explaining each step.”
- Ask for the upgrade. “Now show me the optimal solution. What insight makes it possible? What pattern is this an instance of?”
- Stress-test it. “Generate 10 edge cases — empty input, single element, duplicates, max size, sorted, reverse-sorted. Run my solution against each.”
The pattern matters more than the answer. If the agent just hands you optimized code, you’ve trained yourself to lose interviews.
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
Solution:
We can solve it multiple ways using Breadth First Search and Depth First Search the below solution uses Depth First Search with Back Tracking.
class HackerHeap {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
dfs(root, 0, result);
return result;
}
public void dfs(TreeNode root, int level, List<List<Integer>> rst) {
if (root == null) {
return;
}
if (level >= rst.size()) {
rst.add(0, new ArrayList<Integer>());
}
dfs(root.left, level + 1, rst);
dfs(root.right, level + 1, rst);
rst.get(rst.size() - level - 1).add(root.val);
}
}
For the AI-native engineering side of HackerHeap — building MCP servers, comparing agents (Claude Code, Cursor, Windsurf, Codex, Gemini, Copilot), and weekly working code — see the Friday Build newsletter and the MCP archive.