Easy and short backtracking java code solution


  • 0
    T
    public List<List<Integer>> pathSum(TreeNode root, int sum)  {
    	List<List<Integer>> res = new ArrayList<List<Integer>>();
    	List<Integer> list = new ArrayList<Integer>();
    	helper(root, res, list, sum);
    	return res;
    }
    
    public void helper(TreeNode root, List<List<Integer>> res, List<Integer> list, int sum) {
    	if (root == null) return;
    	sum -= root.val;
    	list.add(root.val);
    	
    	if (sum == 0 && root.left == null && root.right == null) {
    		List<Integer> temp = new ArrayList<Integer>(list);
    		res.add(temp);
    	}
        helper(root.left, res, list, sum);
        helper(root.right, res, list, sum);
        list.remove(list.size() - 1);
    
    }

Log in to reply
 

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