We can find the solution in either of the 3 manners

- Some path adds up to sum from the root (i.e. root is a member of the path)
- Root is not a member of the path and solution lies completely in left sub-tree
- Root is not a member of the path and solution lies completely in right sub- tree

2 & 3 are taken care of by recursion in the function pathSum()

Case 1 is taken care of in pathSumRec() function.

In this the solution can be reached in three steps again.

- Root == sum
- Root + some path in left subtree
- Root + some path in right subtree

```
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSumRec(TreeNode* root, int sum) {
if(root == NULL)
return 0;
int rootmatch = (root->val == sum);
int left = pathSumRec(root->left, sum - root->val);
int right = pathSumRec(root->right, sum - root->val);
return rootmatch + left + right;
}
int pathSum(TreeNode* root, int sum) {
if (root == NULL)
return 0;
int rootval = pathSumRec(root, sum);
int lefttree = pathSum(root->left, sum);
int righttree = pathSum(root->right, sum);
return (rootval + lefttree + righttree);
}
};
```