Very easy to understand and I think it's concise


  • 1
    N

    Just travel the tree in the right side first and then left side.
    If the depth of the current node is >= the list.size(), it means that this is level of element is not in the list yet. then just add it.

    public List<Integer> rightSideView(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            rightSideView(root,0,result);
            return result;
        }
        
        private void rightSideView(TreeNode root,int level,List<Integer> result){
            if(root==null) return;
            if(level>=result.size()){
                result.add(root.val);
            }
            rightSideView(root.right,level+1,result);
            rightSideView(root.left,level+1,result);
        }
    

Log in to reply
 

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