Binary Tree Right Side View
Difficulty: Medium · Pattern: Trees & BST · LeetCode #199
Imagine standing to the right of a binary tree. Return the values of the nodes you can see, ordered from top to bottom.
Examples
text
1 ← see 1
/ \
2 3 ← see 3
\ \
5 4 ← see 4
[1,2,3,null,5,null,4] → [1,3,4]
[1,2,3,4] → [1,3,4] (4 is visible: nothing on its level is further right)Hints
- The visible node on each level is the rightmost node on that level.
- It is not just "follow right children". A deep left subtree can stick out below the right side.
Approach
BFS: for each level, record the value of the last node in it.
DFS alternative: visit right before left, and record a node the first time you reach a new depth (depth == len(result)). Right-first order guarantees the first node seen at each depth is the rightmost one.
The DFS uses O(h) memory instead of O(width), which matters for wide, shallow trees.
Complexity
Time: O(n). Space: O(h) for the DFS, O(w) for the BFS.
Python solution
def rightSideView(root):
out = []
def dfs(node, d):
if not node:
return
if d == len(out):
out.append(node.val)
dfs(node.right, d + 1)
dfs(node.left, d + 1)
dfs(root, 0)
return outJavaScript solution
function rightSideView(root) {
const out = [];
let level = root ? [root] : [];
while (level.length) {
out.push(level[level.length - 1].val);
const next = [];
for (const n of level) { if (n.left) next.push(n.left); if (n.right) next.push(n.right); }
level = next;
}
return out;
}