Provide Best Programming Tutorials

199. Binary Tree Right Side View

Question

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> rlist = new LinkedList<>();
        if(root == null) return rlist;
        
        List<TreeNode> llist = new LinkedList<>();
        llist.add(root);
        
        while(!llist.isEmpty()){
            int size = llist.size();
            List<Integer> ilist = new LinkedList<>();
            for(int i=0;i<size;i++){
                 TreeNode curNode=llist.remove(0);
                 ilist.add(curNode.val);
                 if(curNode.left!=null){
                     llist.add(curNode.left);
                 }
                 if(curNode.right!=null){
                    llist.add(curNode.right);
                }
            }
            
            rlist.add(ilist.remove(ilist.size()-1));
    
        }
        return rlist;
    }
}

 

Leave a Reply

Close Menu