Binary Tree Right Side View
Binary Tree Right Side View is a medium trees & bst problem solved with the views pattern.
The best approach, dfs, right child first, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from bfs, last node per level up.
Problem
Imagine standing on the right side of a binary tree. Return the values you can see, from top to bottom.
Examples
Example 1
- Input
root = [1, 2, 3, null, 5, null, 4]- Output
[1, 3, 4]
Example 2
- Input
root = [1, 2, 3, 4]- Output
[1, 3, 4]- Why
- 4 is on the left, but nothing is to its right on that level.
Constraints
- The tree has
0to100nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| BFS, last node per level | O(n) | O(w) |
| DFS, right child first | O(n) | O(h) |
1BFS, last node per level
O(n)O(w)Record the last node polled on each level.
- For each level record the node at i == size - 1.
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode n = q.poll();
if (i == size - 1) out.add(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
return out;
}
}class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
out = []
if root is None:
return out
q = deque([root])
while q:
size = len(q)
for i in range(size):
n = q.popleft()
if i == size - 1:
out.append(n.val)
if n.left is not None:
q.append(n.left)
if n.right is not None:
q.append(n.right)
return outclass Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> out;
if (root == nullptr) return out;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* n = q.front(); q.pop();
if (i == size - 1) out.push_back(n->val);
if (n->left != nullptr) q.push(n->left);
if (n->right != nullptr) q.push(n->right);
}
}
return out;
}
};function rightSideView(root) {
const out = [];
if (root === null) return out;
let q = [root];
while (q.length > 0) {
const size = q.length;
const next = [];
for (let i = 0; i < size; i++) {
const n = q[i];
if (i === size - 1) out.push(n.val);
if (n.left !== null) next.push(n.left);
if (n.right !== null) next.push(n.right);
}
q = next;
}
return out;
}2DFS, right child first
O(n)O(h)Preorder visiting right before left. The first node reached at each new depth is the rightmost on that level.
- If depth == out.size(), add node.val.
- Recurse right, then left.
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> out = new ArrayList<>();
dfs(root, 0, out);
return out;
}
private void dfs(TreeNode n, int depth, List<Integer> out) {
if (n == null) return;
if (depth == out.size()) out.add(n.val);
dfs(n.right, depth + 1, out);
dfs(n.left, depth + 1, out);
}
}class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
out = []
self.dfs(root, 0, out)
return out
def dfs(self, n: Optional[TreeNode], depth: int, out: List[int]) -> None:
if n is None:
return
if depth == len(out):
out.append(n.val)
self.dfs(n.right, depth + 1, out)
self.dfs(n.left, depth + 1, out)class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> out;
dfs(root, 0, out);
return out;
}
private:
void dfs(TreeNode* n, int depth, vector<int>& out) {
if (n == nullptr) return;
if (depth == (int)out.size()) out.push_back(n->val);
dfs(n->right, depth + 1, out);
dfs(n->left, depth + 1, out);
}
};function rightSideView(root) {
const out = [];
dfs(root, 0, out);
return out;
}
function dfs(n, depth, out) {
if (n === null) return;
if (depth === out.length) out.push(n.val);
dfs(n.right, depth + 1, out);
dfs(n.left, depth + 1, out);
}Edge cases to test
- Empty tree
- A deeper left subtree
Hints
Hint 1
The right view is the last node of each level, or the first node reached at each depth when DFS goes right first.
FAQ
What is the best time complexity for Binary Tree Right Side View?
DFS, right child first runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Right Side View use?
It is a trees & bst problem that uses the views pattern. Other problems with the same pattern: Top View of Binary Tree, Bottom View of Binary Tree, Left View of Binary Tree.
Is there a brute force solution for Binary Tree Right Side View?
Yes. BFS, last node per level takes O(n) time and O(w) space. Record the last node polled on each level.
Which edge cases should I test for Binary Tree Right Side View?
Empty tree; A deeper left subtree.