Trees & BST · Pattern 4 of 12
Tree views: left, right, top, bottom and vertical order
Give every node a coordinate: its level, and a column (left child col - 1, right child col + 1). Each view keeps one node per level or per column; BFS order decides which one.
Watch the lesson
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
When to use it
- What you see from the left, right, top or bottom
- Group nodes by vertical column
- The outline (boundary) of the tree
The template
// right view: the last node of every BFS level (the first one gives the left view)
List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
if (i == size - 1) res.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
}
return res;
}
// top view: BFS with a column per node; the first node seen in a column wins
List<Integer> topView(TreeNode root) {
TreeMap<Integer, Integer> first = new TreeMap<>(); // column -> value, sorted by column
Deque<TreeNode> q = new ArrayDeque<>();
Deque<Integer> cols = new ArrayDeque<>();
if (root != null) { q.offer(root); cols.offer(0); }
while (!q.isEmpty()) {
TreeNode node = q.poll();
int col = cols.poll();
first.putIfAbsent(col, node.val); // bottom view: put(), so the last one wins
if (node.left != null) { q.offer(node.left); cols.offer(col - 1); }
if (node.right != null) { q.offer(node.right); cols.offer(col + 1); }
}
return new ArrayList<>(first.values());
} from collections import deque
# right view: the last node of every BFS level (the first one gives the left view)
def right_side_view(root):
res, q = [], deque([root] if root else [])
while q:
size = len(q)
for i in range(size):
node = q.popleft()
if i == size - 1:
res.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
# top view: BFS with a column per node; the first node seen in a column wins
def top_view(root):
first = {} # column -> value
q = deque([(root, 0)] if root else [])
while q:
node, col = q.popleft()
first.setdefault(col, node.val) # bottom view: first[col] = node.val
if node.left:
q.append((node.left, col - 1))
if node.right:
q.append((node.right, col + 1))
return [first[c] for c in sorted(first)] // right view: the last node of every BFS level (the first one gives the left view)
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front(); q.pop();
if (i == size - 1) res.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
// top view: BFS with a column per node; the first node seen in a column wins
vector<int> topView(TreeNode* root) {
map<int, int> first; // column -> value, sorted by column
queue<pair<TreeNode*, int>> q;
if (root) q.push({root, 0});
while (!q.empty()) {
auto [node, col] = q.front(); q.pop();
first.insert({col, node->val}); // keeps the first; bottom view: first[col] = ...
if (node->left) q.push({node->left, col - 1});
if (node->right) q.push({node->right, col + 1});
}
vector<int> res;
for (auto& [col, val] : first) res.push_back(val);
return res;
} // right view: the last node of every BFS level (the first one gives the left view)
function rightSideView(root) {
const res = [];
let q = root ? [root] : [];
while (q.length) {
res.push(q[q.length - 1].val);
const next = [];
for (const node of q) {
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
q = next;
}
return res;
}
// top view: BFS with a column per node; the first node seen in a column wins
function topView(root) {
const first = new Map(); // column -> value
const q = root ? [[root, 0]] : [];
for (let head = 0; head < q.length; head++) {
const [node, col] = q[head];
if (!first.has(col)) first.set(col, node.val); // bottom view: always set
if (node.left) q.push([node.left, col - 1]);
if (node.right) q.push([node.right, col + 1]);
}
return [...first.keys()].sort((a, b) => a - b).map((c) => first.get(c));
} The variations
-
1One node per level
BFS level by level: the last node of each level is the right view, the first is the left view. A DFS that visits right before left and records the first node at each new depth works too.
Now you solve -
2One node per column
BFS with a column number. Top view keeps the first node seen in each column, bottom view overwrites it with the last. Read the columns from left to right.
Now you solve -
3All nodes by column
Same coordinates, but keep every node in a list per column. BFS order breaks ties for the plain vertical order; the strict version sorts by (row, value) within a column.
Now you solve -
4The outline of the tree
Three parts in order: the left edge top-down (without leaves), every leaf left to right, the right edge bottom-up (without leaves). Add the root once.
Mistakes to avoid
- Top view with DFS: the first node DFS reaches in a column is not always the highest one. Use BFS, or store the level and keep the smallest.
- Vertical order traversal (the strict version): nodes in the same row and column must be sorted by value. Sort by (column, row, value).
- Boundary: counting a leaf twice, once as part of the left edge and once as a leaf.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.