My Java recursive solution accepted, any improvements?


  • 0
    J

    The key point is key let the new arraylist be a parameter for the pathFind function.

        public List<List<Integer>> pathSum(TreeNode root, int sum) {
    	if(root == null){
    	    return new ArrayList<List<Integer>>();
    	}
    	return pathFind(root, sum, new ArrayList<Integer>());
    }
    
    public List<List<Integer>> pathFind(TreeNode node, int sum, List<Integer> list) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	int rest = sum - node.val;
    	if (node.left == null && node.right == null) {
    		if (rest == 0) {
    			list.add(node.val);
    			result.add(list);
    		}
    		return result;
    	}
    
    	list.add(node.val);
    	if (node.left != null) {
    		result.addAll(pathFind(node.left, rest, new ArrayList<Integer>(list)));
    	}
    
    	if (node.right != null) {
    		result.addAll(pathFind(node.right, rest, new ArrayList<Integer>(list)));
    	}
    	return result;
    }

Log in to reply
 

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