In this Leetcode Path Sum III problem solution we have Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

Leetcode Path Sum III problem solution


Problem solution in Python.

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        if not root:
            return 0
        result = 0
        queue = deque()
        queue.append([root, []])
        while queue:
            node, sum_list = queue.popleft()
            new_sum_list = sum_list[:]
            new_sum_list.append(0)
            for k in range(len(new_sum_list)):
                new_sum_list[k] += node.val
                if new_sum_list[k] == sum:
                    result += 1
            if node.left:
                queue.append([node.left, new_sum_list])
            if node.right:
                queue.append([node.right, new_sum_list])
        return result



Problem solution in Java.

int count = 0;
public int pathSum(TreeNode root, int sum) {
    sumPath(root, sum, new ArrayList<Integer>());
    return count;
}

public void sumPath(TreeNode root, int sum, List<Integer> path) {
    if(root == null) return;
    
    path.add(root.val);
    int curSum = 0;
    for(int i = path.size()-1; i >= 0; i--) {
        curSum += path.get(i);
        if(curSum == sum) count++;
    }
    sumPath(root.left, sum, path);
    sumPath(root.right, sum, path);
    path.remove(path.size() -1);
}


Problem solution in C++.

int DFS(TreeNode* root, int sum,int count) {
        if(root==NULL) return 0;
        if(sum-root->val==0) count++;
        return count+DFS(root->left,sum-root->val,0)+DFS(root->right,sum-root->val,0);
    }
    
    int pathSum(TreeNode* root, int sum) {
        if(root==NULL) return 0;
        return DFS(root,sum,0)+pathSum(root->left,sum)+pathSum(root->right,sum);
    }


Problem solution in C.

int pathSumHelper(struct TreeNode* root, int sum, int cur, int inc){
    int ret = 0;
    
    if (root == NULL)
        return 0;

    if ((cur + root->val) == sum)
        ret = 1;

    ret += pathSumHelper(root->left, sum, cur + root->val, inc + 1);
    ret += pathSumHelper(root->right, sum, cur + root->val, inc + 1);
    
    if (inc == 0) {
        ret += pathSumHelper(root->left, sum, 0, 0);
        ret += pathSumHelper(root->right, sum, 0, 0);
    }
    
    return ret;
}

int pathSum(struct TreeNode* root, int sum){
    return pathSumHelper(root, sum, 0, 0);
}