classSolution{List<List<Integer>> res;publicList<List<Integer>>pathSum(TreeNode root,int targetSum){
res =newArrayList<>();// Check root validityif(root ==null)return res;// Start lookingdfs(root, targetSum,newArrayList<Integer>(),0);return res;}privatevoiddfs(TreeNode node,int targetSum,List<Integer> path,int sum){// Reached the endif(node ==null)return;// Record current node values sum
sum += node.val;// Add current node to the path
path.add(node.val);// Check left and rightdfs(node.left, targetSum, path, sum);dfs(node.right, targetSum, path, sum);// Check is leaf and same with the targetSumif(node.left ==null&& node.right ==null&& sum == targetSum){
res.add(newArrayList<>(path));}// Remove the last node to maintain correct path
path.remove(path.size()-1);}}