Path Sum (2 versions)

Abhinay Gupta
1 min readJul 6, 2021

--

Path Sum 1

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.

class Solution {
int sum=0;
int target=0;
public boolean hasPathSum(TreeNode root, int targetSum) {
this.target=targetSum;
return sum(root,0);

}
public boolean sum(TreeNode root, int curr){
if(root!=null){
curr=curr+root.val;
if(root.left==null&&root.right==null){
return target==curr;
}
return sum(root.left,curr)||sum(root.right,curr);
}
return false;
}
}

Path Sum 2

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. A leaf is a node with no children

class Solution {int target=0;
List<List<Integer>> ans;
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
ans= new ArrayList();
this.target=targetSum;
sum(root,0, new ArrayList());
return ans;

}
public void sum(TreeNode root, int curr,List<Integer> list){
if(root!=null){
curr=curr+root.val;
list.add(root.val);
if(root.left==null&&root.right==null){
if(curr==target){
ans.add(new ArrayList(list));
}
}
sum(root.left,curr,list);
sum(root.right,curr,list);
list.remove(list.size()-1);
}
return;
}
}

--

--

Abhinay Gupta

Exploring personal growth, tech, and culture through engaging storytelling | Inspiring and connecting with readers worldwide.