Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom.
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Tree (view from right):
1 ← see 1
/ \
2 3 ← see 3 (rightmost)
\ \
5 4 ← see 4 (rightmost)
Input: root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]
Tree:
1 ← see 1
/ \
2 3 ← see 3
/
4 ← see 4 (only node at level 2)
/
5 ← see 5
Input: root = [1,null,3]
Output: [1,3]
Input: root = []
Output: []
From the right side, we see the rightmost node at each level.
Two approaches:
Both work, but BFS is more intuitive for "level" problems.
This is a BFS Level Processing problem with:
Visit right child before left:
def dfs(node, depth):
if not node: return
if depth == len(result): # First node at this depth
result.append(node.val)
dfs(node.right, depth + 1) # Right first!
dfs(node.left, depth + 1)
This works because we visit right child first, so the first node we see at each depth is the rightmost.
Time: O(n) where n = number of nodes
Space: O(w) where w = maximum width
1import java.util.*;
2
3class TreeNode {
4 int val;
5 TreeNode left;
6 TreeNode right;
7 TreeNode() {}
8 TreeNode(int val) { this.val = val; }
9 TreeNode(int val, TreeNode left, TreeNode right) {
10 this.val = val;
11 this.left = left;
12 this.right = right;
13 }
14}
15
16class Solution {
17 public List<Integer> rightSideView(TreeNode root) {
18 List<Integer> result = new ArrayList<>();
19
20 if (root == null) {
21 return result;
22 }
23
24 Queue<TreeNode> queue = new LinkedList<>();
25 queue.offer(root);
26
27 while (!queue.isEmpty()) {
28 int levelSize = queue.size();
29 int rightmost = 0;
30
31 // Process all nodes in current level
32 for (int i = 0; i < levelSize; i++) {
33 TreeNode node = queue.poll();
34 rightmost = node.val; // Keep updating, last will be rightmost
35
36 // Add children for next level
37 if (node.left != null) {
38 queue.offer(node.left);
39 }
40 if (node.right != null) {
41 queue.offer(node.right);
42 }
43 }
44
45 // Add rightmost node of this level
46 result.add(rightmost);
47 }
48
49 return result;
50 }
51}
52