13. Binary Tree Right Side View
mediumAsked at Byju'sReturn the rightmost node visible at each level of a binary tree.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
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. Each level contributes its rightmost visible node.
Constraints
0 <= nodes <= 100-100 <= Node.val <= 100
Examples
Example 1
root = [1,2,3,null,5,null,4][1,3,4]Example 2
root = [1,null,3][1,3]Approaches
1. Level-order then take last
Do a full level-order traversal then keep the last value of each level array.
- Time
- O(n)
- Space
- O(n)
const levels=[],q=root?[root]:[];
while(q.length){const lvl=[],s=q.length;for(let i=0;i<s;i++){const n=q.shift();lvl.push(n.val);if(n.left)q.push(n.left);if(n.right)q.push(n.right);}levels.push(lvl);}
return levels.map(l=>l[l.length-1]);Tradeoff:
2. DFS right-first
Recurse right child first and record the first node encountered at each depth. The first visit at depth d is always the rightmost.
- Time
- O(n)
- Space
- O(h)
function rightSideView(root) {
const res = [];
const dfs = (n, d) => {
if (!n) return;
if (d === res.length) res.push(n.val);
dfs(n.right, d + 1);
dfs(n.left, d + 1);
};
dfs(root, 0);
return res;
}Tradeoff:
Byju's-specific tips
Byju's interviewers expect you to verbalize tree traversal in lesson-style, because their K-12 explainers depend on candidate communication clarity.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Binary Tree Right Side View and other Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →