Binary Tree Right Side View
TreesBFS / DFS
Problem Statement
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.
Example
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Solution 1: Breadth-First Search (BFS)
The BFS approach traverses the tree level by level. For each level, the rightmost node is the one we can see from the right side.
Algorithm Steps
- Create a queue and add the root node.
- While the queue is not empty, get the number of nodes at the current level.
- For each level, the last node is the rightmost one. Add its value to the result list.
- Enqueue the children of the nodes at the current level.
Right Side View: []
Start of level. Level size: 1.
Binary Tree Right Side View Solution
Solution 2: Depth-First Search (DFS)
The DFS approach traverses the tree, keeping track of the current level. The first time we visit a level, we add the node's value to our result list. Since we traverse the right subtree first, the first node we see at each level will be the rightmost one.
Algorithm Steps
- Create a recursive function that takes the current node and level as arguments.
- If the current level is equal to the size of our result list, it means we're visiting this level for the first time. Add the node's value to the list.
- Recursively call the function on the right child first, then the left child.
Right Side View: []
Visiting node 1 at level 0.
Binary Tree Right Side View Solution