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