Binary Tree Right Side View

Preorder DFS visiting right before left — first node seen at each depth is the rightmost.

Medium
Time O(n) Space O(h)
LeetCode
2 min read
tree dfs

Problem#

Return the values of the nodes visible when looking at the tree from the right side, top to bottom.

Examples#

  • [1,2,3,null,5,null,4][1,3,4]
  • [1,null,3][1,3]
  • [][]

Constraints#

  • The number of nodes is in [0, 100].

Approach#

DFS visiting right child first. If the current depth equals the answer’s current length, this is the first (rightmost) node at this level — append.

Solution#

Binary Tree Right Side View
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
function<void(TreeNode*, int)> dfs = [&](TreeNode* u, int depth) {
if (!u) return;
if ((int)ans.size() == depth) ans.push_back(u->val);
dfs(u->right, depth + 1);
dfs(u->left, depth + 1);
};
dfs(root, 0);
return ans;
}
};

Editorial#

Visiting right before left guarantees the first node seen at each depth is the rightmost. The depth-equals-size guard ensures we only record the first such node per level.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.