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<Integer> rightSideView(TreeNode root) {
    ArrayList<Integer> result = new ArrayList<Integer>();
 
    if(root == null) return result;
 
    LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
 
    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)
            if(i==0){
                result.add(top.val);
            }
            //add right first
            if(top.right != null){
                queue.add(top.right);
            }
            //add left
            if(top.left != null){
                queue.add(top.left);
            }
        }
    }
 
    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:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Amit Sharma on 2015-6-30

    Find the below link for another solution for same problem
    http://amitanjani.blogspot.in/2015/06/print-left-view-and-right-view-of.html

  2. Iram22 on 2017-2-14


    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);
    }

  3. Hooman on 2017-4-9

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

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

    Queue queue = new LinkedList();
    Queue depth = new LinkedList();
    List res = new ArrayList();

    queue.add(root);
    depth.add(1);

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

    if (depth.isEmpty()) {
    res.add(top.val);
    }
    else if (lvl < depth.peek()) {
    res.add(top.val);
    }

    if (top.left != null) {
    queue.add(top.left);
    depth.add(lvl + 1);
    }
    if (top.right != null) {
    queue.add(top.right);
    depth.add(lvl + 1);
    }

    }

    return res;
    }

Leave a comment

*