Skip to main content

Binary Tree Right Side View


Binary Tree Right Side View: Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example 1:

image

Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Example 2:
Input: root = [1,null,3]
Output: [1,3]

Example 3:
Input: root = []
Output: []

Constraints:
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Try this Problem on your own or check similar problems:

  1. Populating Next Right Pointers in Each Node
Solution:
class Solution {
public List<Integer> rightSideView(TreeNode root) {
if(root == null) return List.of();

List<Integer> result = new ArrayList<>();
helper(root, 0, result);
return result;
}

private void helper(TreeNode root, int level, List<Integer> result){
if(root == null) return;
if(level == result.size()){
result.add(root.val);
}else{
result.set(level, root.val);
}
helper(root.left, level + 1, result);
helper(root.right, level + 1, result);
}
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

We can utilize the DFS approach to traverse tree and hold a list which keeps reference to last element in each of tree levels. To keep the track of level we pass level parameter, and we start with the root and 0-level. We can also utilize the BFS tree level traversal we implemented in Binary Tree Level Order Traversal and for each level insert the last node we traverse over (size == 0):

public List<Integer> rightSideView(TreeNode root) {
if(root == null) return List.of();

Queue<TreeNode> q = new LinkedList<>();
List<Integer> result = new ArrayList<>();

q.add(root);

while(!q.isEmpty()){
int size = q.size();
while(size-->0){
TreeNode node = q.poll();
if(node.left != null){
q.add(node.left);
}
if(node.right != null){
q.add(node.right);
}
if(size == 0){
result.add(node.val);
}
}
}
return result;
}