top of page
Search

Binary Tree Right Side View

Updated: Mar 25, 2021

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.



Example:

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

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

Solution:


class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root==null) return result;
        queue.offer(root);
        while(!queue.isEmpty())
        {
            int size = queue.size();
            for(int i=0;i<size;i++)
            {
                TreeNode currentNode = queue.poll();
                if(i==0) result.add(currentNode.val);
                if(currentNode.right!=null) queue.offer(currentNode.right);
                if(currentNode.left!=null) queue.offer(currentNode.left);
            }
        }
        return result;
    }
}


8 views0 comments

Recent Posts

See All

Comments


bottom of page