Skip to content

Commit 24b13e3

Browse files
authored
Create README.md
1 parent 2de81bb commit 24b13e3

File tree

1 file changed

+168
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/27 - K Sum Paths

1 file changed

+168
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
<h1 align='center'>K - Sum - Paths</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [K Sum Paths](https://www.geeksforgeeks.org/problems/k-sum-paths/1)
6+
7+
![image](https://github.com/user-attachments/assets/c08e276a-48f1-40f4-9fe4-9a423a3a5e50)
8+
![image](https://github.com/user-attachments/assets/41375ba2-a1ec-4f9d-833f-d334ae1598b8)
9+
10+
## Problem Explanation
11+
**Problem:** In a binary tree, find the number of paths that sum up to a given integer \( k \). These paths:
12+
- Do not need to start at the root or end at a leaf, but they must move downwards through parent-child connections.
13+
14+
**Real-World Analogy:** Imagine a tree where each node has a value representing the weight of packages. We need to find all paths of packages that add up to a certain weight. These paths don't need to start at the beginning of a branch or end at the leaf but must follow a continuous path downwards.
15+
16+
**Constraints:**
17+
- A path may start and end anywhere in the tree, but must follow a downward direction.
18+
- Paths can overlap partially or be entirely contained within larger paths.
19+
20+
**Example:**
21+
If we have the following binary tree:
22+
```
23+
1
24+
/ \
25+
3 -1
26+
/ \ / \
27+
2 1 4 5
28+
/ \ \
29+
1 2 6
30+
```
31+
and we’re given \( k = 5 \), the paths that sum up to 5 are:
32+
- Path `3 -> 2`
33+
- Path `3 -> 1 -> 1`
34+
- Path `1 -> 4`
35+
- Path `-1 -> 5 -> 1`
36+
37+
The output here should be 4.
38+
39+
### Step 2: Approach
40+
41+
To solve this problem efficiently:
42+
1. **Traverse Each Node:** Start from each node in the tree and check if any downward paths (starting from that node) sum to \( k \).
43+
2. **Backtracking and Path Storage:** For each node visited, add its value to a list (representing the current path from root to the node).
44+
3. **Check All Possible Sums:** Starting from the current node, check the sum of each possible path ending at the current node to see if it equals \( k \).
45+
4. **Count Paths that Match:** For every match of the sum with \( k \), increment a counter.
46+
## Problem Solution
47+
```cpp
48+
class Solution {
49+
public:
50+
void solve(Node* root, int k, vector<int> path, int &count){
51+
if(root == NULL) return;
52+
53+
path.push_back(root -> data);
54+
55+
solve(root -> left, k, path, count);
56+
solve(root -> right, k, path, count);
57+
58+
int size = path.size();
59+
int sum = 0;
60+
for(int i = size -1; i >= 0; i--){
61+
sum += path[i];
62+
63+
if(sum == k) count++;
64+
}
65+
66+
path.pop_back();
67+
}
68+
int sumK(Node *root, int k) {
69+
vector<int> path;
70+
int count = 0;
71+
72+
solve(root, k, path, count);
73+
74+
return count;
75+
}
76+
};
77+
```
78+
79+
## Problem Solution Explanation
80+
81+
1. **`void solve(Node* root, int k, vector<int> path, int &count)`**
82+
- This is a recursive helper function used to traverse the tree and count paths that sum to \( k \).
83+
- **Parameters:**
84+
- `root`: Current node in the traversal.
85+
- `k`: Target sum.
86+
- `path`: A vector that stores the current path from the root to the current node.
87+
- `count`: Reference to the count of paths summing to \( k \).
88+
89+
2. **Base Case: `if (root == NULL) return;`**
90+
- If `root` is `NULL`, the function returns without doing anything, which ends recursion for branches reaching a leaf’s end.
91+
92+
3. **Add Current Node’s Value to `path`: `path.push_back(root->data);`**
93+
- Adds the current node’s value to the `path` vector. This stores values from the root to the current node, so we can calculate all possible path sums ending at this node.
94+
95+
4. **Recursive Calls on Left and Right Subtrees**
96+
- `solve(root->left, k, path, count);`
97+
- `solve(root->right, k, path, count);`
98+
- These lines initiate recursive calls on the left and right child nodes, continuing the path.
99+
100+
5. **Loop to Calculate Sums for All Paths Ending at the Current Node**
101+
```cpp
102+
int size = path.size();
103+
int sum = 0;
104+
for (int i = size - 1; i >= 0; i--) {
105+
sum += path[i];
106+
if (sum == k) count++;
107+
}
108+
```
109+
- **Explanation:**
110+
- Starting from the end of `path`, which is the current node, it accumulates values backward towards the root.
111+
- If any accumulated sum equals \( k \), the `count` variable is incremented.
112+
- This approach ensures that all paths ending at the current node are checked for a sum of \( k \).
113+
114+
6. **Backtracking: `path.pop_back();`**
115+
- After all calculations for the current node are done, remove its value from `path` to backtrack. This prepares the `path` for the next sibling or ancestor node in the recursive stack.
116+
117+
7. **Main Function `int sumK(Node *root, int k)`**
118+
- Initializes `path` and `count` and calls the helper function `solve`.
119+
- After traversal, it returns the final count of paths that sum to \( k \).
120+
121+
### Step 4: Output Examples
122+
123+
- **Example 1:**
124+
```
125+
Input Tree: 1
126+
/ \
127+
3 -1
128+
/ \ / \
129+
2 1 4 5
130+
/ / \ \
131+
1 1 2 6
132+
Target Sum (k): 5
133+
134+
Output: 4
135+
Explanation: Four paths sum to 5:
136+
- 3 -> 2
137+
- 3 -> 1 -> 1
138+
- 1 -> 4
139+
- -1 -> 5 -> 1
140+
```
141+
142+
- **Example 2:**
143+
```
144+
Input Tree: 10
145+
/
146+
-5
147+
/ \
148+
3 8
149+
/
150+
2
151+
Target Sum (k): 8
152+
153+
Output: 2
154+
Explanation: Two paths sum to 8:
155+
- 10 -> -5 -> 3
156+
- 8
157+
```
158+
159+
### Step 5: Time and Space Complexity
160+
161+
- **Time Complexity:** \(O(N^2)\)
162+
- The complexity is \(O(N^2)\) in the worst case because for each node, we check all paths leading to it, which can take up to \(N\) operations (for nodes closer to the root in a skewed tree).
163+
164+
- **Space Complexity:** \(O(N)\)
165+
- The `path` vector stores up to \(N\) nodes in the worst case, where \(N\) is the number of nodes in the binary tree. Additionally, recursion uses \(O(H)\) space, where \(H\) is the tree height.
166+
167+
### Summary
168+
This solution is efficient for moderately sized binary trees and demonstrates how to approach path-related problems with recursion and backtracking, calculating possible path sums at each step to determine if they match the target.

0 commit comments

Comments
 (0)