count
to 0 to store the number of valid paths.h
to store the frequency of prefix sums.preorder(node, curr_sum)
that takes the current node and the current prefix sum as arguments.preorder
, add the value of the current node to curr_sum
.curr_sum
equals the target sum, increment count
by 1.count
by the frequency of curr_sum - targetSum
from the hashmap.curr_sum
in the hashmap by 1.preorder
for the left and right children of the current node with the updated curr_sum
.curr_sum
in the hashmap by 1 to avoid counting paths from parallel subtrees.count
after the traversal is complete.