List the nodes you'd see standing to the right of a binary tree. Walk it level by level and keep the last node on each level.
▼The problem
LeetCode 199 (Medium). Given the root of a binary tree, imagine standing on its right side and return the values of the nodes you can see, ordered from top to bottom: the last node of every level.
- Title scene (illustrative): [7,2,9,4,null,5] → [7,9,5] (5 is a left child, still last on its level). - LeetCode's first example: [1,2,3,null,5,null,4] → [1,3,4]; following right children also gives [1,3,4] here. - The trap (ours): [1,2,3,4] → [1,3,4], where 4 hangs under 2 on the left; the right path gives [1,3] and misses 4. - The walkthrough (ours): [1,2,3,4,5,null,6,7] → [1,3,6,7] (7 is alone, far left, on level four).
The solution
def rightSideView(root):
view = []
level = [root] if root else []
while level:
view.append(level[-1].val)
level = [kid for node in level
for kid in (node.left, node.right) if kid]
return viewTranscript
Binary Tree Right Side View. Picture a binary tree with the sun setting on its right. On each level, the low light hits only the nearest node, the one you'd see standing on that side. Return those values, from top to bottom.
Here's the first example. One is the root, with children two and three. Two has a right child, five, and three has a right child, four. The first ray finds one. The second passes straight to three. The third hits four, and five sits in its shadow. So the answer is one, three, four.
It looks like you could just slide down the right children: one, three, four. That works here. But try this tree: one, two, three, and a four hanging under two, on the left. The right path stops at three, yet nothing on four's level blocks the light. The answer is one, three, four, so the shortcut misses four.
So go level by level, breadth first. Keep each level's nodes in order, left to right. The last one is always the node the sun hits. Then build the next level from their children, left child before right.
In code, start with a level holding just the root, or nothing for an empty tree. While the level has nodes, add the value of its last node to the view. Then replace the level with all of their children, in order. When a level comes up empty, return the view.
Let's run it on a bigger tree. Level one is just one, so one is seen. Level two is two, three: three is last. Level three is four, five, six: six is last. Level four holds only seven, far out on the left. But it's last on its level, so the sun reaches it. The view is one, three, six, seven.
Each node joins a level once, so the time is O of n. We hold only one level at a time, so the extra space is O of the widest level.
Level by level, keep the last one. That's Binary Tree Right Side View.