VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-k-sum-paths-binary-tree/

⇱ Print all k-sum paths in a binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all k-sum paths in a binary tree

Last Updated : 23 Jul, 2025

A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. 
A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree.

Examples:

Input : k = 5 
Root of below binary tree:
1
/ \
3 -1
/ \ / \
2 1 4 5
/ / \ \
1 1 2 6

Output :
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5

Source : Amazon Interview Experience Set-323

Kindly note that this problem is significantly different from finding k-sum path from root to leaves. Here each node can be treated as root, hence the path can start and end at any node.

Approach:
The basic idea to solve the problem is to do a preorder traversal of the given tree. We also need a container (vector) to keep track of the path that led to that node. At each node we check if there are any path that sums to k, if any we print the path and proceed recursively to print each path.

Code:

Below is the implementation of the same. 


Output
3 2 
3 1 1 
1 3 1 
4 1 
1 -1 4 1 
-1 4 2 
5 
1 -1 5 

Time complexity: O(N^2), where N is the number of nodes in the binary tree. This is because for each node, we traverse the entire path (up to N nodes) to check if there exists a path with a sum equal to k.
Auxiliary space: O(N) because in the worst case, the path vector can store up to N nodes. Additionally, the recursive calls consume stack space proportional to the height of the tree, which can be at most N in the case of a skewed tree.

This article is contributed by Ashutosh Kumar

Comment
Article Tags:
Article Tags: