It seems that instead of looping over the the path at each node, a sliding window can be used. So the worst case becomes O(nlogn)
Proposed solution:
def count_paths(root, S):
if root is None:
return 0
return count_paths_rec(root, S, [], 0, 0)
def count_paths_rec(node, S, cur_path, cur_sum, start):
cur_path.append(node.val)
cur_sum += node.val
# advance start of path
while cur_sum > S and start < len(cur_path)-1:
cur_sum -= cur_path[start]
start += 1
count = 0
if cur_sum == S:
count += 1
for child in (node.left, node.right):
if child is not None:
count += count_paths_rec(child, S, cur_path, cur_sum, start)
cur_path.pop()
return count
Please let me know if there’s something I’m missing