# Java recursive solution accepted. Anything to improve it?

• 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) {
} //else re is empty
return re;
}

if(node.left!=null)
if(node.right!=null)
return re;
}
``````

}

• 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.

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.

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