So let's say the problem is calculating the number of paths in a binary tree whose sum is equal to some target.
One simple way to do this is to recursively call DFS twice for each child, once for using child node for a path that started somewhere before it and once to start searching for path starting at child node.
Time complexity of this approach would be O(4^k), where k is the height of the tree, but what would be the complexity in respect to the number of nodes n in the tree?
I know that regular DFS has O(n) time complexity since it visits each tree node only once, but this approach would visit node at level m 2^m times if I'm not mistaken.
Here is my code for the problem in python.
def cnt_paths(root, target):
return dfs(root, target, 0, set())
def dfs(node, target, current_sum, visited):
cnt = 0
if current_sum + node.val == target:
cnt += 1
if node.left:
cnt += dfs(node.left, target, current_sum + node.val, visited) # include this node
if node.left not in visited:
cnt += dfs(node.left, target, 0, visited) # start from scratch on next node
visited.add(node.left)
if node.right:
cnt += dfs(node.right, target, current_sum + node.val, visited)
if node.right not in visited:
cnt += dfs(node.right, target, 0, visited)
visited.add(node.right)
return cnt