# LeetCode – Binary Tree Right Side View (Java)

Given 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. For example, given the following binary tree,

1            <---
/   \
2     3         <---
\
5             <---

You can see [1, 3, 5].

Analysis

This problem can be solve by using a queue. On each level of the tree, we add the right-most element to the results.

Java Solution

 public List rightSideView(TreeNode root) { ArrayList result = new ArrayList();   if(root == null) return result;   LinkedList queue = new LinkedList(); queue.add(root);   while(queue.size() > 0){ //get size here int size = queue.size();   for(int i=0; i

Similarly, we can also use two queues which makes the code slightly more readable.

 public List rightSideView(TreeNode root) { LinkedList q1 = new LinkedList<>(); LinkedList q2 = new LinkedList<>();   ArrayList result = new ArrayList<>(); if (root == null) { return result; }   q1.offer(root); q2.offer(1); int prev = 0;   while (!q1.isEmpty()) { TreeNode h = q1.poll(); int level = q2.poll();   if (level != prev) { result.add(h.val); }   if (h.right != null) { q1.offer(h.right); q2.offer(level + 1); }   if (h.left != null) { q1.offer(h.left); q2.offer(level + 1); }   prev = level; }   return result; }

### 3 thoughts on “LeetCode – Binary Tree Right Side View (Java)”

1. Here’s a O(n) solution. Just like Leet 117:

public List rightSideView(TreeNode root) {
if (root == null) {
return new ArrayList();
}

List res = new ArrayList();

while (!queue.isEmpty()) {
int lvl = depth.poll();
TreeNode top = queue.poll();

if (depth.isEmpty()) {
}
else if (lvl < depth.peek()) {
}

if (top.left != null) {
}
if (top.right != null) {
}

}

return res;
}

2. private static void rightView(Node n,int lvl,int arr[]){
if(n==null) return;
arr[lvl]=n.val;
rightView(n.left,lvl+1,arr);
rightView(n.right,lvl+1,arr);
}