Binary Tree K-Sum Paths Problem
Given a binary tree where each node contains an integer value, and a number 'K', your task is to find and output all paths in the tree where the sum of the node values equals 'K'. The paths must travel downwards from parent nodes to child nodes.
Input:
The input starts with an integer 'T' denoting the number of test cases. For each test case, two lines follow:
The first line presents elements of the tree in level order, separated by a space. Use -1 for any null node.
The second line contains an integer 'K', representing the target path sum.
Output:
For each test case, output all paths where node values sum up to 'K'. Print paths in the order they appear in the tree, left to right, one per line.
Example:
Example for K = 4:
Input Tree: 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
K: 4
Output Paths:
1 3
3 1
-1 4 1
4
-1 5
Constraints:
- 1 <= T <= 50
- 1 <= N <= 102
- -109 <= K <= 109
- -107 <= DATA <= 107
Where 'N' represents the number of nodes, 'K' is the path sum to find, and 'DATA' is the value at each tree node.
Note:
You do not need to print anything directly. Implement the function to return the correct paths. Paths should be identified as sequences of node values, respecting the tree's left-to-right order.
Be the first one to answer
Add answer anonymously...
Top UST Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app