Java recursive solution accepted. Anything to improve it?


  • 0
    5

    There is my Java solution.

    public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        if(root==null) return re;
        
        re.addAll( pathSum(root, sum, new ArrayList<Integer>()) );
        return re;
    }
    
    public List<List<Integer>> pathSum(TreeNode node, int sum, List<Integer> list) {
    
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        int rest = sum - node.val;
        if(node.left==null && node.right==null) { //if it's a leaf node
            if(rest==0) {
                list.add(node.val);
                re.add(list);
            } //else re is empty
            return re;
        }
        
        list.add(node.val);
        if(node.left!=null) 
            re.addAll(pathSum(node.left, rest, new ArrayList<Integer>(list)) );
        if(node.right!=null) 
            re.addAll(pathSum(node.right, rest, new ArrayList<Integer>(list)) );
        return re;
    }
    

    }


  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example

    Pay attention to "Writing code? Select all code then click on the {} button to preserve code formatting.” above text editor.


  • 0
    J
    1. in your pathSum function, it is not necessary to declare "re". just use:
      return pathSum(root, sum, new ArrayList<Integer>());

    2. pathSum function name can be changed to make code clearer.


Log in to reply
 

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