Binary tree right side view
What a tree looks like standing to its right: the last node visible on every level.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Run a level-order BFS and, on each level, keep only the last node dequeued. That node is the one standing farthest to the right on its level, since the queue always empties a level left to right. Collecting that one node per level, top to bottom, gives the sequence of nodes visible from the right side.
Code
public static List<int> RightSideView(TreeNode root) {
var result = new List<int>();
var queue = new Queue<TreeNode>();
if (root != null) queue.Enqueue(root);
while (queue.Count > 0) {
int count = queue.Count;
for (int i = 0; i < count; i++) {
TreeNode node = queue.Dequeue();
if (i == count - 1) result.Add(node.val);
if (node.left != null) queue.Enqueue(node.left);
if (node.right != null) queue.Enqueue(node.right);
}
}
return result;
}static List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
if (root != null) queue.offer(root);
while (!queue.isEmpty()) {
int count = queue.size();
for (int i = 0; i < count; i++) {
TreeNode node = queue.poll();
if (i == count - 1) result.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return result;
}vector<int> rightSideView(TreeNode* root) {
vector<int> result;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int count = (int)q.size();
for (int i = 0; i < count; i++) {
TreeNode* node = q.front(); q.pop();
if (i == count - 1) result.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return result;
}from collections import deque
def right_side_view(root: TreeNode | None) -> list[int]:
result = []
queue = deque()
if root: queue.append(root)
while queue:
count = len(queue)
for i in range(count):
node = queue.popleft()
if i == count - 1: result.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return resultTips
- A depth-first version instead visits the right child before the left, and records the first node seen at each new depth.
In the .NET library
The left side view is the exact mirror: either take the first node dequeued per BFS level, or do the DFS version visiting left before right.