Simple Java solution using HashMap and tree traversal


  • 0
    C
    public List<Integer> rightSideView(TreeNode root) {
        HashMap<Integer, Integer> temp=new HashMap<Integer,Integer>();
        addRightMost(0,root, temp);
        List<Integer> result=new ArrayList(temp.values());
        return result;
    }
    
    public void addRightMost(int level, TreeNode root,HashMap<Integer,Integer> temp){
        if(root==null) return;
        if(!temp.containsKey(level)){
            temp.put(level,root.val);
        }
        if(root.right!=null){
            addRightMost(level+1, root.right,temp);
        }
        if(root.left!=null){
            addRightMost(level+1, root.left,temp);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.