Clean and short, O(n) solution in java, Easy to understand with comments


  • 0
    V
    /**
    * Key idea is to add all the element from right side and then only those from the left side whose depth is greater than the max of right side.
    */    
    public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            addRightSide(root,0,result);
            return result;
        }
        
        private void addRightSide(TreeNode root,int level, List<Integer> result){
            if(root == null) return ;
            if(result.size() == level) result.add(root.val); // only add if level is not present.
            addRightSide(root.right,level + 1, result);
            addRightSide(root.left,level + 1,result);
    
        }

  • 0
    V

    runs in 1 ms and beats 85% of the submissions.


Log in to reply
 

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