Easy Java recursive solution with comments.


  • 0
    P
    public  List<List<Integer>> pathSum(TreeNode root, int sum) { // List based recursive solution. Good one.
    		List<List<Integer>> result = new ArrayList<>();
    		if (root == null)
    			return result;
    		helper(result, new ArrayList<Integer>(), root, sum);
    		return result;
    	}
    
    	private  void helper(List<List<Integer>> res, List<Integer> list, TreeNode node, int sum) {
    		if (node == null)
    			return;
    		if (node.left == null && node.right == null && node.val == sum) {
    			list.add(node.val);
    			res.add(new ArrayList<>(list));
    			list.remove(list.size() - 1); //remove the last element and return so that you dont add the last element again.
    			return;
    		}
    		list.add(node.val);
    
    		if (node.left != null)
    			helper(res, list, node.left, sum - node.val);
    
    		if (node.right != null)
    			helper(res, list, node.right, sum - node.val);
    
    		list.remove(list.size() - 1); //remove last element when done searching both the sides.
    
    	}
    	```

Log in to reply
 

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