Hi guys,

Instead of calculating pathSum on every node. Another approach could be to use a sliding window for maintaining path sum. I believe time complexity will be improved to O(N log N).

O(N) for traversing the tree.

For the sliding window, all paths will be accessed once. So total paths( (N+1) / 2) * height of balanced Tree (log N) elements will be accessed.

O((N+1) / 2 * log N) => O(N log N)

O(N) + O (N log N) => O (N log N) should be the time complexity.

What are your thoughts?

```
private static int findPaths(TreeNode root, int reqSum) {
List<Integer> currentPath = new ArrayList<>();
return findPathRecursively(root, currentPath, 0, reqSum, 0);
}
private static int findPathRecursively(
TreeNode node,
List<Integer> currentPath,
int prevSum,
int reqSum,
int begIndex
) {
if (node == null) {
return 0;
}
currentPath.add(node.getValue());
int currSum = prevSum + node.getValue();
int matchedPaths = 0;
while (currSum >= reqSum) {
if (currSum == reqSum) {
matchedPaths++;
}
currSum -= currentPath.get(begIndex);
begIndex++;
}
int leftMatchedPaths = findPathRecursively(node.getLeftNode(), currentPath, currSum, reqSum,
begIndex);
int rightMatchedPaths = findPathRecursively(node.getRightNode(), currentPath, currSum, reqSum,
begIndex);
currentPath.remove(currentPath.size() - 1);
return leftMatchedPaths + rightMatchedPaths + matchedPaths;
}
```

Thanks