Recursive solution


  • 10
    N
    public class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            
            if(root == null) return res;
            
            visitLevel(root, 1, res);
            return res;
        }
        
        public void visitLevel(TreeNode root, int level, List<Integer> res){
            
            if(root == null) return;
            if(level > res.size()){
                res.add(root.val);    
            }
            
            visitLevel(root.right, level+1, res);
            visitLevel(root.left, level+1, res);
        }
    }

  • 0
    K

    Here, is res passed by reference or by value? Thanks.


  • 0
    Q

    I think it's reference.


  • 0
    K

    But why, there is no & in the function argument list. I asked this question because I thought it's by value, and I wondered why the efficiency was still quite high. Perhaps the data to be copied is too small to make any observable difference?


  • 0
    Q

    in the method visitlevel, res is just like a pointer or a address linked to a block of heap memory, when we call the recursive method many times, the method just make some changes in the original heap memory.


  • 0
    K

    I thought this is C++, my stupid mistake, sorry!
    No more problems.
    Hope you're interested, here is my C++ solution in 7 ms (which uses almost identical algorithm):
    https://leetcode.com/discuss/33191/18-line-recursive-c-solution-in-7-ms


Log in to reply
 

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