What you see from the right
List the nodes visible when you look at a tree from its right side, which is the last node of each row, using the row-by-row walk. About 12 minutes.
One node per row
Imagine standing to the right of a tree and looking left. On each level, the node nearest to you hides all the others on that level. So you see exactly one node per level: the rightmost one.
It is not always the right child of the previous visible node. If the right side of the tree is shorter than the left, the visible node on a deep level lives on the left.
row = [1, 3, 4] last = row[-1]
- view
- [5]
Row 1 has only 5, so 5 is visible.
Find the last of each row
Use the row-by-row walk. At the start of each row, note how many nodes it has. While taking the row's nodes, remember the value of the one that was taken last, or compare the position to the row size minus one.
Add that value to the answer after the row. Reading the rows top to bottom gives the view from top to bottom. An empty tree has an empty view.
for i in range(size):
if i == size - 1:
last = i # the last in the rowA level has the nodes 7, 4, 9 from left to right. Which one is visible from the right?
- A9, the last one
- B7, the first one
- CAll three
Show the answer
9, the last one. It is the rightmost node on the level.
Binary tree right side view
Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered from top to bottom. A node is visible if no other node on its level lies to its right. An empty tree gives an empty list.
root = [1, 2, 3, null, 5, null, 4] → [1, 3, 4]
0 ≤ number of nodes ≤ 100 · -100 ≤ node.val ≤ 100