-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path06_PathProblems.cpp
More file actions
399 lines (294 loc) · 12.3 KB
/
Copy path06_PathProblems.cpp
File metadata and controls
399 lines (294 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
================================================================================
TREE PATH PROBLEMS
================================================================================
Problems involving paths in trees - root to leaf, any to any, path sums.
================================================================================
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
/*
PROBLEM 1: Path Sum (LeetCode 112)
──────────────────────────────────
Check if root-to-leaf path with given sum exists.
Time: O(n) | Space: O(h)
*/
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) {
return root->val == targetSum;
}
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
/*
PROBLEM 2: Path Sum II (LeetCode 113)
─────────────────────────────────────
Find all root-to-leaf paths with given sum.
Time: O(n²) | Space: O(n)
*/
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> result;
vector<int> path;
function<void(TreeNode*, int)> dfs = [&](TreeNode* node, int remaining) {
if (!node) return;
path.push_back(node->val);
if (!node->left && !node->right && remaining == node->val) {
result.push_back(path);
}
dfs(node->left, remaining - node->val);
dfs(node->right, remaining - node->val);
path.pop_back();
};
dfs(root, targetSum);
return result;
}
/*
PROBLEM 3: Path Sum III (LeetCode 437) ⭐ GOOGLE FAVORITE
────────────────────────────────────────────────────────
Count paths that sum to target (can start/end anywhere).
Use prefix sum with hashmap.
Time: O(n) | Space: O(n)
*/
int pathSumIII(TreeNode* root, int targetSum) {
unordered_map<long long, int> prefixCount;
prefixCount[0] = 1;
int count = 0;
function<void(TreeNode*, long long)> dfs = [&](TreeNode* node, long long currSum) {
if (!node) return;
currSum += node->val;
if (prefixCount.count(currSum - targetSum)) {
count += prefixCount[currSum - targetSum];
}
prefixCount[currSum]++;
dfs(node->left, currSum);
dfs(node->right, currSum);
prefixCount[currSum]--;
};
dfs(root, 0);
return count;
}
/*
PROBLEM 4: Binary Tree Maximum Path Sum (LeetCode 124) ⭐ GOOGLE FAVORITE
─────────────────────────────────────────────────────────────────────────
Find maximum sum path (any node to any node).
Time: O(n) | Space: O(h)
*/
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
function<int(TreeNode*)> maxGain = [&](TreeNode* node) -> int {
if (!node) return 0;
int leftGain = max(0, maxGain(node->left));
int rightGain = max(0, maxGain(node->right));
// Path through this node
maxSum = max(maxSum, node->val + leftGain + rightGain);
// Return max single path from this node
return node->val + max(leftGain, rightGain);
};
maxGain(root);
return maxSum;
}
/*
PROBLEM 5: Sum Root to Leaf Numbers (LeetCode 129)
──────────────────────────────────────────────────
Each path represents a number. Find total sum.
Time: O(n) | Space: O(h)
*/
int sumNumbers(TreeNode* root) {
int total = 0;
function<void(TreeNode*, int)> dfs = [&](TreeNode* node, int num) {
if (!node) return;
num = num * 10 + node->val;
if (!node->left && !node->right) {
total += num;
return;
}
dfs(node->left, num);
dfs(node->right, num);
};
dfs(root, 0);
return total;
}
/*
PROBLEM 6: Binary Tree Paths (LeetCode 257)
───────────────────────────────────────────
Return all root-to-leaf paths as strings.
Time: O(n²) | Space: O(n)
*/
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
function<void(TreeNode*, string)> dfs = [&](TreeNode* node, string path) {
if (!node) return;
path += to_string(node->val);
if (!node->left && !node->right) {
result.push_back(path);
return;
}
path += "->";
dfs(node->left, path);
dfs(node->right, path);
};
dfs(root, "");
return result;
}
/*
PROBLEM 7: Longest Univalue Path (LeetCode 687)
───────────────────────────────────────────────
Longest path where all nodes have same value.
Time: O(n) | Space: O(h)
*/
int longestUnivaluePath(TreeNode* root) {
int maxPath = 0;
function<int(TreeNode*)> dfs = [&](TreeNode* node) -> int {
if (!node) return 0;
int left = dfs(node->left);
int right = dfs(node->right);
int leftPath = (node->left && node->left->val == node->val) ? left + 1 : 0;
int rightPath = (node->right && node->right->val == node->val) ? right + 1 : 0;
maxPath = max(maxPath, leftPath + rightPath);
return max(leftPath, rightPath);
};
dfs(root);
return maxPath;
}
/*
PROBLEM 8: Pseudo-Palindromic Paths (LeetCode 1457)
───────────────────────────────────────────────────
Count paths where digit frequencies allow palindrome.
Time: O(n) | Space: O(h)
*/
int pseudoPalindromicPaths(TreeNode* root) {
int count = 0;
function<void(TreeNode*, int)> dfs = [&](TreeNode* node, int mask) {
if (!node) return;
mask ^= (1 << node->val); // Toggle bit for this digit
if (!node->left && !node->right) {
// Palindrome possible if at most one bit set
if ((mask & (mask - 1)) == 0) count++;
return;
}
dfs(node->left, mask);
dfs(node->right, mask);
};
dfs(root, 0);
return count;
}
/*
PROBLEM 9: Smallest String Starting From Leaf (LeetCode 988)
────────────────────────────────────────────────────────────
Find lexicographically smallest leaf-to-root path.
Time: O(n²) | Space: O(n)
*/
string smallestFromLeaf(TreeNode* root) {
string result = "";
function<void(TreeNode*, string)> dfs = [&](TreeNode* node, string path) {
if (!node) return;
path = char('a' + node->val) + path; // Prepend
if (!node->left && !node->right) {
if (result.empty() || path < result) {
result = path;
}
return;
}
dfs(node->left, path);
dfs(node->right, path);
};
dfs(root, "");
return result;
}
/*
PROBLEM 10: Count Good Nodes in Binary Tree (LeetCode 1448)
───────────────────────────────────────────────────────────
Node is good if no node on path from root has greater value.
Time: O(n) | Space: O(h)
*/
int goodNodes(TreeNode* root) {
int count = 0;
function<void(TreeNode*, int)> dfs = [&](TreeNode* node, int maxSoFar) {
if (!node) return;
if (node->val >= maxSoFar) {
count++;
maxSoFar = node->val;
}
dfs(node->left, maxSoFar);
dfs(node->right, maxSoFar);
};
dfs(root, INT_MIN);
return count;
}
/*
PROBLEM 11: Longest ZigZag Path (LeetCode 1372)
───────────────────────────────────────────────
Alternate left-right moves.
Time: O(n) | Space: O(h)
*/
int longestZigZag(TreeNode* root) {
int maxLen = 0;
// direction: 0 = came from left, 1 = came from right
function<void(TreeNode*, int, int)> dfs = [&](TreeNode* node, int direction, int len) {
if (!node) return;
maxLen = max(maxLen, len);
if (direction == 0) { // Go right to continue zigzag
dfs(node->right, 1, len + 1);
dfs(node->left, 0, 1); // Reset
} else {
dfs(node->left, 0, len + 1);
dfs(node->right, 1, 1); // Reset
}
};
dfs(root->left, 0, 1);
dfs(root->right, 1, 1);
return maxLen;
}
// ═══════════════════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════════════════
int main() {
cout << "=== Tree Path Problems ===\n\n";
// Build tree: [5,4,8,11,null,13,4,7,2,null,null,5,1]
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(4);
root->right = new TreeNode(8);
root->left->left = new TreeNode(11);
root->left->left->left = new TreeNode(7);
root->left->left->right = new TreeNode(2);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(4);
root->right->right->left = new TreeNode(5);
root->right->right->right = new TreeNode(1);
// Path Sum
cout << "1. Has path sum 22: " << (hasPathSum(root, 22) ? "Yes" : "No") << "\n";
// Path Sum III
cout << "3. Paths with sum 8: " << pathSumIII(root, 8) << "\n";
// Max Path Sum
cout << "4. Max path sum: " << maxPathSum(root) << "\n";
// Sum Numbers
TreeNode* root2 = new TreeNode(1);
root2->left = new TreeNode(2);
root2->right = new TreeNode(3);
cout << "5. Sum of numbers: " << sumNumbers(root2) << "\n";
return 0;
}
/*
================================================================================
SUMMARY
================================================================================
+───────────────────────────────+────────────────────────────────────────────────+
| Problem | Key Technique |
+───────────────────────────────+────────────────────────────────────────────────+
| Root-to-leaf sum | DFS with remaining target |
| All paths with sum | Backtracking with path vector |
| Path sum anywhere | Prefix sum with hashmap |
| Max path (any-to-any) | Track max gain at each node |
| Path as number | num = num * 10 + node->val |
| Pseudo-palindromic | Bitmask for digit frequency |
+───────────────────────────────+────────────────────────────────────────────────+
PATTERN: Most path problems use DFS with state tracking.
================================================================================
*/