DSA AnimatorREVISION VIDEOS
← Back to problems
New

Binary Tree Right Side View — LeetCode 199 video explanation

Imagine standing on the right side of a binary tree. Return the values you can see, from top to bottom.

Loading videos…

DSA Animator › DSA Revision › Tree › Binary Tree Right Side View

Key moments in the Binary Tree Right Side View video

0:05Problem0:13Example0:27Brute force0:41Key idea0:57Dry run1:23Code1:41Takeaway

What you will learn

Remember: the right side view is the last node of every level. Following right children alone is a trap. The video solves Binary Tree Right Side View (LeetCode 199, Medium) with the BFS Level Order pattern from the Tree topic, and you can replay every step in the interactive Binary Tree Right Side View animation.

Binary Tree Right Side View video transcript

Problem

Imagine standing on the right side of a binary tree. Return the values you can see, from top to bottom.

Example

For the tree 1, with children 2 and 3, where 2 has a right child 5 and 3 has a right child 4, the answer is 1, 3, 4. On each level, you only see the node that is furthest to the right.

Brute force

It is tempting to just follow right children from the root. But that fails when a left subtree is deeper, because then a left node is the rightmost one on its level. So we really need the last node of every level.

Key idea

Run a breadth first search, one level at a time. Within a level, nodes come out of the queue from left to right. So the last node popped in each level is the one visible from the right. Add exactly that node to the answer.

Dry run

Level 0 holds only 1, so 1 is visible. Level 1 holds 2 and 3, and 3 is popped last, so 3 is visible. Level 2 holds 5 and 4. 5 comes from the left subtree, but 4 is popped last, so 4 is visible. The answer is 1, 3, 4. If 3 had no child 4, then 5 would be visible, even though it sits in the left subtree.

Code

In code, loop while the queue is not empty and read the size n. Poll n nodes, pushing their left and right children. When the index equals n minus 1, add that node to the result. It's O of n time and O of the tree width in space.

Takeaway

Remember: the right side view is the last node of every level. Following right children alone is a trap.

More Tree revision videos

← All 185 DSA revision videos