Binary Tree Right Side View
The key idea
From the right side you see exactly one node per level: the last node on that level. So the answer is the rightmost node at each depth. Walk the tree level by level (or depth by depth) and keep the last value you reach on each level.
Problem
Given the root of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom. From any given level you can only see the node that is furthest to the right, because the nodes in front of it block your view.
Constraints
- The number of nodes in the tree is in the range
[0, 100]. -100 <= Node.val <= 100
Examples
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Input: root = [1,null,3]
Output: [1,3]
Input: root = []
Output: []
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More BFS / DFS problems
- 01 MatrixMEDIUM
- Average of Levels in Binary TreeEASY
- Binary Tree Level Order TraversalMEDIUM
- Binary Tree Level Order Traversal IIMEDIUM
- Binary Tree Zigzag Level Order TraversalMEDIUM
- Find Bottom Left Tree ValueMEDIUM
- Find Largest Value in Each Tree RowMEDIUM
- Flood FillEASY
- Keys and RoomsMEDIUM
- Max Area of IslandMEDIUM
- Maximum Level Sum of a Binary TreeMEDIUM
- Minimum Depth of Binary TreeEASY