20. K Sum Paths

The problem can be found at the following link: Question Link

My Approach

To solve the problem,

  • I traverse the tree using a recursive depth-first search (DFS) approach.

  • I maintain a running sum as I traverse the tree and use an unordered map to keep track of the cumulative sums encountered so far.

  • At each node, I check if the complement of the current sum (i.e., currSum - k) exists in the map.

    • If it does, it means there is a path with the required sum, and I update the result.

Time and Auxiliary Space Complexity

  • Time Complexity: O(N), where N is the number of nodes in the tree.

  • Auxiliary Space Complexity: O(N), due to the usage of an unordered map for tracking sums.

Code (C++)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.

Last updated

Was this helpful?