Bottom View of Binary Tree
Bottom View of Binary Tree is a medium trees & bst problem solved with the views pattern.
The best approach, bfs with columns (last seen wins), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs tracking the deepest node per column up.
Problem
Return the bottom view of a binary tree: for each vertical column, the node you see when looking up from below, ordered from left to right.
Examples
Example 1
- Input
root = [20, 8, 22, 5, 3, null, 25, null, null, 10, 14]- Output
[5, 10, 3, 14, 25]
Example 2
- Input
root = [1, 2, 3]- Output
[2, 1, 3]
Constraints
- The tree has
1to10^5nodes. - If two nodes share the deepest position in a column, take the later one in level order.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS tracking the deepest node per column | O(n log n) | O(n) |
| BFS with columns (last seen wins) | O(n) | O(n) |
1DFS tracking the deepest node per column
O(n log n)O(n)DFS with (column, depth). For each column keep the node with the greatest depth; on equal depth, keep the later visit.
- Replace when depth >= stored depth.
- Read the TreeMap in order.
class Solution {
public ArrayList<Integer> bottomView(TreeNode root) {
TreeMap<Integer, int[]> best = new TreeMap<>();
dfs(root, 0, 0, best);
ArrayList<Integer> out = new ArrayList<>();
for (int[] v : best.values()) out.add(v[1]);
return out;
}
private void dfs(TreeNode n, int col, int depth, TreeMap<Integer, int[]> best) {
if (n == null) return;
int[] cur = best.get(col);
if (cur == null || depth >= cur[0]) best.put(col, new int[] { depth, n.val });
dfs(n.left, col - 1, depth + 1, best);
dfs(n.right, col + 1, depth + 1, best);
}
}class Solution:
def bottomView(self, root: Optional[TreeNode]) -> List[int]:
best: Dict[int, List[int]] = {}
self.dfs(root, 0, 0, best)
out = []
for col in sorted(best):
out.append(best[col][1])
return out
def dfs(self, n: Optional[TreeNode], col: int, depth: int, best: Dict[int, List[int]]) -> None:
if n is None:
return
cur = best.get(col)
if cur is None or depth >= cur[0]:
best[col] = [depth, n.val]
self.dfs(n.left, col - 1, depth + 1, best)
self.dfs(n.right, col + 1, depth + 1, best)class Solution {
public:
vector<int> bottomView(TreeNode* root) {
map<int, pair<int, int>> best;
dfs(root, 0, 0, best);
vector<int> out;
for (auto& [col, v] : best) out.push_back(v.second);
return out;
}
private:
void dfs(TreeNode* n, int col, int depth, map<int, pair<int, int>>& best) {
if (n == nullptr) return;
auto it = best.find(col);
if (it == best.end() || depth >= it->second.first) best[col] = {depth, n->val};
dfs(n->left, col - 1, depth + 1, best);
dfs(n->right, col + 1, depth + 1, best);
}
};function bottomView(root) {
const best = new Map();
dfs(root, 0, 0, best);
const out = [];
const cols = [...best.keys()].sort((a, b) => a - b);
for (const c of cols) out.push(best.get(c)[1]);
return out;
}
function dfs(n, col, depth, best) {
if (n === null) return;
const cur = best.get(col);
if (cur === undefined || depth >= cur[0]) best.set(col, [depth, n.val]);
dfs(n.left, col - 1, depth + 1, best);
dfs(n.right, col + 1, depth + 1, best);
}2BFS with columns (last seen wins)
O(n)O(n)In level order, overwrite each column's value every time you reach it. The last write is the deepest node, and later in level order on ties.
- Queue of (node, col); map.put(col, val) always.
- Output from min column to max column.
class Solution {
public ArrayList<Integer> bottomView(TreeNode root) {
Map<Integer, Integer> last = new HashMap<>();
Queue<TreeNode> q = new ArrayDeque<>();
Queue<Integer> cols = new ArrayDeque<>();
q.add(root); cols.add(0);
int min = 0, max = 0;
while (!q.isEmpty()) {
TreeNode n = q.poll();
int c = cols.poll();
last.put(c, n.val);
min = Math.min(min, c); max = Math.max(max, c);
if (n.left != null) { q.add(n.left); cols.add(c - 1); }
if (n.right != null) { q.add(n.right); cols.add(c + 1); }
}
ArrayList<Integer> out = new ArrayList<>();
for (int c = min; c <= max; c++) out.add(last.get(c));
return out;
}
}class Solution:
def bottomView(self, root: Optional[TreeNode]) -> List[int]:
last: Dict[int, int] = {}
q = deque([root])
cols = deque([0])
mn, mx = 0, 0
while q:
n = q.popleft()
c = cols.popleft()
last[c] = n.val
mn = min(mn, c); mx = max(mx, c)
if n.left is not None:
q.append(n.left); cols.append(c - 1)
if n.right is not None:
q.append(n.right); cols.append(c + 1)
out = []
for c in range(mn, mx + 1):
out.append(last[c])
return outclass Solution {
public:
vector<int> bottomView(TreeNode* root) {
unordered_map<int, int> last;
queue<TreeNode*> q;
queue<int> cols;
q.push(root); cols.push(0);
int mn = 0, mx = 0;
while (!q.empty()) {
TreeNode* n = q.front(); q.pop();
int c = cols.front(); cols.pop();
last[c] = n->val;
mn = min(mn, c); mx = max(mx, c);
if (n->left != nullptr) { q.push(n->left); cols.push(c - 1); }
if (n->right != nullptr) { q.push(n->right); cols.push(c + 1); }
}
vector<int> out;
for (int c = mn; c <= mx; c++) out.push_back(last[c]);
return out;
}
};function bottomView(root) {
const last = new Map();
const q = [root];
const cols = [0];
let head = 0;
let min = 0, max = 0;
while (head < q.length) {
const n = q[head];
const c = cols[head];
head++;
last.set(c, n.val);
min = Math.min(min, c); max = Math.max(max, c);
if (n.left !== null) { q.push(n.left); cols.push(c - 1); }
if (n.right !== null) { q.push(n.right); cols.push(c + 1); }
}
const out = [];
for (let c = min; c <= max; c++) out.push(last.get(c));
return out;
}Edge cases to test
- Nodes at the same column and depth
Hints
Hint 1
It is the top view with 'last seen wins' instead of 'first seen wins'.
FAQ
What is the best time complexity for Bottom View of Binary Tree?
BFS with columns (last seen wins) runs in O(n) time and O(n) extra space.
Which pattern does Bottom View of Binary Tree use?
It is a trees & bst problem that uses the views pattern. Other problems with the same pattern: Top View of Binary Tree, Left View of Binary Tree, Binary Tree Right Side View.
Is there a brute force solution for Bottom View of Binary Tree?
Yes. DFS tracking the deepest node per column takes O(n log n) time and O(n) space. DFS with (column, depth).
Which edge cases should I test for Bottom View of Binary Tree?
Nodes at the same column and depth.