Binary Tree Right Side View
Pattern: Views and boundaries
From the right you see the last node of each level. A depth-first walk that visits the right child first sees that node first at each new depth, so record a node whenever its depth equals the number of values so far.
The problem
Return the values seen when looking at the tree from the right side, from top to bottom: the rightmost node of each
level. [3, 9, 20, null, null, 15, 7] gives [3, 20, 7]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Which node of each level is seen from the right?
- In level order, how do you find it?
- Can a depth-first walk find it with less work?
Hints
Brute force, and why it fails
Level order, taking the last of each level: also O(n).
The key insight
Visiting right before left makes the first node seen at every depth the rightmost one.
Dry run
| out | 3 |
|---|
Tree [3, 9, 20, null, null, 15, 7]. Depth 0: 3 is new, record it.
The plan
see(n, d): if n is null: return
if d == len(out): out.append(n.val)
see(n.right, d + 1); see(n.left, d + 1)
Complexity
- Time
O(n)- Space
O(h)
Each node is visited once.
Edge cases
- A left-only chain: every node is seen.
- Empty tree.
- One node.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> out = new ArrayList<>();
see(root, 0, out);
return out;
}
private void see(TreeNode node, int depth, List<Integer> out) { // right child first
if (node == null) return;
if (depth == out.size()) out.add(node.val); // the first node reached at a new depth is the rightmost
see(node.right, depth + 1, out);
see(node.left, depth + 1, out);
}
}C++
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> out;
see(root, 0, out);
return out;
}
void see(TreeNode* node, int depth, vector<int>& out) { // right child first
if (node == NULL) return;
if (depth == static_cast<int>(out.size())) out.push_back(node->val); // first at a new depth is the rightmost
see(node->right, depth + 1, out);
see(node->left, depth + 1, out);
}
};Python
class Solution:
def rightSideView(self, root) -> list[int]:
out = []
def see(node, depth): # right child first
if node:
if depth == len(out):
out.append(node.val) # the first node reached at a new depth is the rightmost
see(node.right, depth + 1)
see(node.left, depth + 1)
see(root, 0)
return outCommon mistakes
- Going left first, which gives the left view.
- Recording every right child (a left node can be visible when the right side is shorter).