Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Rightmost Node

LeetCode #199Medium
Right-side view = last node of each level

Given the root of a binary tree, imagine standing on its right side and return the values of the nodes visible from top to bottom, that is the rightmost node of each level.

Asked atAmazonMetaMicrosoft
step 1 / 11
binary tree
2
5
1
3
4
queue (FIFO)
front →
(empty)
← back
BFS, take last of level
1rightSideView(root):
2 queue = [root]
3 while queue not empty:
4 levelSize = len(queue)
5 for i in range(levelSize):
6 node = queue.dequeue()
7 if i == levelSize - 1: rightView.append(node.val)
8 enqueue node.children
9 return rightView
state
  • targetlast node per level

line 1LeetCode 199 — the right-side view: standing to the right of the tree, which node do you see on each level? It is the LAST node dequeued in that level. The level-batching loop hands us each level in left-to-right order, so the final one of the batch is exactly what is visible.