Recursive solution of Java code.


  • 0
    O

    The problem can be solved recursively, here is the accepted java code:

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> arr = new ArrayList<List<Integer>>(), larr, rarr;
            if(root == null) {
                return arr;
            }
            else if(root.val == sum && root.left == null && root.right == null) {
            	arr.add(new ArrayList<Integer>(Arrays.asList(root.val)));
            }
            
            if((larr = pathSum(root.left, sum - root.val)).size() != 0) {
                for(List<Integer> item : larr){
                	item.add(0, root.val);
                }
                arr.addAll(larr);
            }
            
            if((rarr = pathSum(root.right, sum - root.val)).size() != 0) {
                for(List<Integer> item : rarr) {
                    item.add(0, root.val);
                }
                arr.addAll(rarr);
            }
            return arr;
        }
    

Log in to reply
 

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