Binary Tree Right Side View
You're given the root of a binary tree. Picture standing to its right: on each level you see only the rightmost node, and the rest of that level is hidden behind it. Return the visible values from the root down to the deepest level. A level's rightmost node can be a left child when nothing sits further right. An empty tree returns an empty list. Example trees are listed row by row from the top, each row left to right, with null where a child is missing.
Examples
root = [1,2,3,null,5,null,4] returns [1,3,4]
The rightmost node on each level is 1, then 3, then 4. The 5 on the bottom level is hidden behind 4, which sits further right.
root = [1,null,3] returns [1,3]
The root 1 has only a right child 3, so each level has a single node and both are visible.
root = [1,2,3,4,null,null,null,5] returns [1,3,4,5]
The third level holds only 4, the left child of 2, so it is visible even though it is on the left. Below it, 5 is alone on the fourth level.
Constraints
- 0 <= number of nodes <= 100
Hints
From each row of the tree, which single node is visible from the right side?
Do BFS level by level; record the last node visited at each level.
Standard level-order BFS. For each level, iterate exactly queue.size() pops, and when i == size - 1 push that node's value into the result.
Drill This: Your Approach First
Approach
Traverse level by level with a queue. For each level, snapshot the queue's size, pop that many nodes while pushing their children left then right, and record the value of the last node popped (index size - 1). Because children are pushed left to right, the last node of each level is the rightmost one at that depth, wherever its parent is. O(n) time, O(n) space for the queue.
Time
O(n)
Space
O(n)
Pitfall
Solutions
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
Deque<TreeNode> queue = new ArrayDeque<>();
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) result.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return result;
}
}from collections import deque
class Solution:
def rightSideView(self, root):
result = []
if not root:
return result
queue = deque([root])
while queue:
size = len(queue)
for i in range(size):
node = queue.popleft()
if i == size - 1:
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result