def count_paths(root, S, prevNums = []):
if root is None:
return 0
prevNums.append(root.val)
numOfPaths, total = 0, 0
# We are at a leaf node
if root.left is None and root.right is None:
for i in range(len(prevNums) -1, -1, -1):
total += prevNums[i]
if total == S:
numOfPaths += 1
else:
numOfPaths += count_paths(root.left, S, prevNums)
numOfPaths += count_paths(root.right, S, prevNums)
del(prevNums[-1])
return numOfPaths
Wouldn’t this achieve the same solution with a linear time complexity?