Binary Tree Right Side View
Preorder DFS visiting right before left — first node seen at each depth is the rightmost.
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#
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; }};func rightSideView(root *TreeNode) []int { ans := []int{} var dfs func(u *TreeNode, depth int) dfs = func(u *TreeNode, depth int) { if u == nil { return } if len(ans) == depth { ans = append(ans, u.Val) } dfs(u.Right, depth+1) dfs(u.Left, depth+1) } dfs(root, 0) return ans}from typing import List, Optional
class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: ans: List[int] = []
def dfs(u: Optional[TreeNode], depth: int) -> None: if not u: return if len(ans) == depth: ans.append(u.val) dfs(u.right, depth + 1) dfs(u.left, depth + 1)
dfs(root, 0) return ansvar rightSideView = function(root) { const ans = []; const dfs = (u, depth) => { if (!u) return; if (ans.length === depth) ans.push(u.val); dfs(u.right, depth + 1); dfs(u.left, depth + 1); }; dfs(root, 0); return ans;};class Solution { private List<Integer> ans = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) { dfs(root, 0); return ans; }
private void dfs(TreeNode u, int depth) { if (u == null) return; if (ans.size() == depth) ans.add(u.val); dfs(u.right, depth + 1); dfs(u.left, depth + 1); }}function rightSideView(root: TreeNode | null): number[] { const ans: number[] = []; const dfs = (u: TreeNode | null, depth: number): void => { if (!u) return; if (ans.length === depth) ans.push(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#
Related#