LeetCode75-199-BT-Right-Side-View

🧠 Summary of Thoughts

Idea

Use level-order traversal (BFS) to process the tree level by level. For each level, record the last node because it represents the node visible from the right side.

Steps

  • Use a queue to perform BFS.

  • For each level, get the number of nodes: size = queue.size().

  • Traverse all nodes in that level.

  • When visiting the last node of the level (i == size - 1), add its value to the result.

  • Push the node’s left and right children into the queue.

When to use BFS?

  1. Level by Level
  2. shortest path
  3. spread from one spot

✅ Code(Java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == size - 1) {
res.add(node.val);
}
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, 0, res);
return res;
}
private void dfs (TreeNode node, int depth, List<Integer> res) {
if (node == null) return;
// If it is the first time to this level, then add the rightmost node.val to the res
if (depth == res.size()) {
res.add(node.val);
}
dfs(node.right, depth + 1, res);
dfs(node.left, depth + 1, res);
}
}

LeetCode75-199-BT-Right-Side-View
https://powersixxx.github.io/leetcode-blog/2026/03/07/LeetCode75-199-BT-Right-Side-View/
作者
Baowen Liu
发布于
2026年3月7日
许可协议