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].


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<Integer> rightSideView(TreeNode root) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    if(root == null) return result;
    LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
    while(queue.size() > 0){
        //get size here
        int size = queue.size();
        for(int i=0; i<size; i++){
            TreeNode top = queue.remove();
            //the first element in the queue (right-most of the tree)
            //add right first
            if(top.right != null){
            //add left
            if(top.left != null){
    return result;
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";