-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0112_path_sum.html
More file actions
471 lines (396 loc) · 17.7 KB
/
0112_path_sum.html
File metadata and controls
471 lines (396 loc) · 17.7 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 112: Path Sum - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#112</span> Path Sum</h1>
<p>Given a binary tree and a target sum, determine if there is a root-to-leaf path where node values sum to target.</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">🔄 DFS</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(h)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0112_path_sum/0112_path_sum.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Use <strong>DFS</strong> to explore all root-to-leaf paths:</p>
<ul>
<li><strong>Subtract:</strong> At each node, subtract its value from remaining sum</li>
<li><strong>Leaf Check:</strong> At a leaf, check if remaining sum = 0</li>
<li><strong>Backtrack:</strong> If path doesn't work, try another</li>
<li><strong>Early Exit:</strong> Return true as soon as we find a valid path</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="startBtn" onclick="start()">▶ Start DFS</button>
<button class="btn" onclick="stepForward()">Step →</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
<label style="margin-left: 15px;">Target Sum: </label>
<input type="number" id="targetInput" value="22" style="width: 80px; padding: 8px; border-radius: 5px; border: 2px solid #ddd;" onchange="reset()">
</div>
<div class="status-message" id="statusMessage">
Click Start to search for a path with target sum
</div>
<div style="display: flex; gap: 20px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 2; min-width: 400px;">
<svg id="treeViz" width="100%" height="350"></svg>
</div>
<div style="flex: 1; min-width: 200px;">
<h4>📍 Current Path</h4>
<div id="pathDisplay" style="padding: 15px; background: #fff3e0; border-radius: 12px; margin-bottom: 15px; min-height: 40px;"></div>
<h4>➕ Path Sum</h4>
<div id="sumDisplay" style="padding: 20px; background: #e3f2fd; border-radius: 12px; margin-bottom: 15px; font-size: 1.5em; text-align: center; font-weight: bold;"></div>
<h4>🎯 Target</h4>
<div id="targetDisplay" style="padding: 20px; background: #f3e5f5; border-radius: 12px; margin-bottom: 15px; font-size: 1.5em; text-align: center; font-weight: bold; color: #9c27b0;">
22
</div>
<h4>✅ Result</h4>
<div id="resultDisplay" style="padding: 20px; background: #e8f5e9; border-radius: 12px; font-size: 1.3em; text-align: center; font-weight: bold; color: #666;">
Searching...
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution (DFS)</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Path Sum
Problem from LeetCode: https://leetcode.com/problems/path-sum/
Description:
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is 5 -> 4 -> 11 -> 2.
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 -> 2): The sum is 3.
(1 -> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def has_path_sum(self, root: Optional[TreeNode], targetSum: int) -> bool:
"""
Check if there is a root-to-leaf path with the given sum.
Args:
root: Root of the binary tree
targetSum: Target sum to find
Returns:
bool: True if a path with the target sum exists, False otherwise
"""
# Base case: empty tree
if not root:
return False
# Subtract the current node's value from the target
targetSum -= root.val
# If this is a leaf node, check if the target sum is reached
if not root.left and not root.right:
return targetSum == 0
# Recursively check left and right subtrees
return (self.has_path_sum(root.left, targetSum) or
self.has_path_sum(root.right, targetSum))
def has_path_sum_iterative(self, root: Optional[TreeNode], targetSum: int) -> bool:
"""
Iterative approach using a stack.
Args:
root: Root of the binary tree
targetSum: Target sum to find
Returns:
bool: True if a path with the target sum exists, False otherwise
"""
if not root:
return False
# Stack to store nodes and their accumulated sum
stack = [(root, root.val)]
while stack:
node, current_sum = stack.pop()
# Check if this is a leaf node with the target sum
if not node.left and not node.right and current_sum == targetSum:
return True
# Add right child to the stack
if node.right:
stack.append((node.right, current_sum + node.right.val))
# Add left child to the stack
if node.left:
stack.append((node.left, current_sum + node.left.val))
return False
# Helper function to create a binary tree from a list
def create_tree(values, index=0):
if not values or index >= len(values) or values[index] is None:
return None
root = TreeNode(values[index])
root.left = create_tree(values, 2 * index + 1)
root.right = create_tree(values, 2 * index + 2)
return root
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
tree1 = create_tree([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1])
target_sum1 = 22
result1 = solution.has_path_sum(tree1, target_sum1)
print(f"Example 1: targetSum={target_sum1}, result={result1}") # Expected output: True
# Example 2
# 1
# / \
# 2 3
tree2 = create_tree([1, 2, 3])
target_sum2 = 5
result2 = solution.has_path_sum(tree2, target_sum2)
print(f"Example 2: targetSum={target_sum2}, result={result2}") # Expected output: False
# Example 3
tree3 = None
target_sum3 = 0
result3 = solution.has_path_sum(tree3, target_sum3)
print(f"Example 3: targetSum={target_sum3}, result={result3}") # Expected output: False
# Compare with iterative approach
print("\nUsing iterative approach:")
print(f"Example 1: {solution.has_path_sum_iterative(tree1, target_sum1)}")
print(f"Example 2: {solution.has_path_sum_iterative(tree2, target_sum2)}")
print(f"Example 3: {solution.has_path_sum_iterative(tree3, target_sum3)}")
</pre>
</div>
</div>
</div>
<script>
const tree = {
val: 5, id: 1, x: 250, y: 40,
left: {
val: 4, id: 2, x: 130, y: 110,
left: {
val: 11, id: 4, x: 70, y: 180,
left: { val: 7, id: 8, x: 40, y: 250, left: null, right: null },
right: { val: 2, id: 9, x: 100, y: 250, left: null, right: null }
},
right: null
},
right: {
val: 8, id: 3, x: 370, y: 110,
left: { val: 13, id: 6, x: 310, y: 180, left: null, right: null },
right: {
val: 4, id: 7, x: 430, y: 180,
left: null,
right: { val: 1, id: 10, x: 460, y: 250, left: null, right: null }
}
}
};
let targetSum = 22;
let currentPath = [];
let currentSum = 0;
let visitedNodes = new Set();
let successPath = [];
let isRunning = false;
let stepIndex = 0;
let steps = [];
function flattenTree(node, arr = []) {
if (!node) return arr;
arr.push(node);
flattenTree(node.left, arr);
flattenTree(node.right, arr);
return arr;
}
function precomputeSteps() {
steps = [];
function dfs(node, path, sum) {
if (!node) return false;
const newPath = [...path, node.val];
const newSum = sum + node.val;
steps.push({
type: 'visit',
nodeId: node.id,
path: newPath,
sum: newSum,
message: `Visit node ${node.val}, path sum = ${newSum}`
});
const isLeaf = !node.left && !node.right;
if (isLeaf) {
if (newSum === targetSum) {
steps.push({
type: 'found',
path: newPath,
sum: newSum,
message: `🎯 Found! Path [${newPath.join(' → ')}] sums to ${targetSum}`
});
return true;
} else {
steps.push({
type: 'leaf_fail',
path: newPath,
sum: newSum,
message: `Leaf reached: ${newSum} ≠ ${targetSum}, backtrack`
});
return false;
}
}
if (node.left) {
if (dfs(node.left, newPath, newSum)) return true;
}
if (node.right) {
if (dfs(node.right, newPath, newSum)) return true;
}
steps.push({
type: 'backtrack',
path: path,
sum: sum,
message: `Backtrack from ${node.val}`
});
return false;
}
const found = dfs(tree, [], 0);
if (!found) {
steps.push({
type: 'not_found',
message: `No path found that sums to ${targetSum}`
});
}
}
function render() {
const svg = d3.select("#treeViz");
svg.selectAll("*").remove();
const container = svg.node().parentElement;
const width = container.clientWidth;
const height = 350;
svg.attr("viewBox", `0 0 ${width} ${height}`);
const nodes = flattenTree(tree);
const g = svg.append("g").attr("transform", `translate(${(width - 500) / 2}, 0)`);
// Draw edges
function drawEdges(node) {
if (!node) return;
if (node.left) {
const onPath = currentPath.includes(node.val) && currentPath.includes(node.left.val);
g.append("line")
.attr("x1", node.x).attr("y1", node.y)
.attr("x2", node.left.x).attr("y2", node.left.y)
.attr("stroke", onPath ? "#4caf50" : "#ccc")
.attr("stroke-width", onPath ? 4 : 2);
drawEdges(node.left);
}
if (node.right) {
const onPath = currentPath.includes(node.val) && currentPath.includes(node.right.val);
g.append("line")
.attr("x1", node.x).attr("y1", node.y)
.attr("x2", node.right.x).attr("y2", node.right.y)
.attr("stroke", onPath ? "#4caf50" : "#ccc")
.attr("stroke-width", onPath ? 4 : 2);
drawEdges(node.right);
}
}
drawEdges(tree);
// Draw nodes
nodes.forEach(node => {
const onPath = currentPath.includes(node.val);
const onSuccess = successPath.includes(node.val);
const isLeaf = !node.left && !node.right;
let fill = "#667eea";
if (onPath) fill = "#ff9800";
if (onSuccess) fill = "#4caf50";
g.append("circle")
.attr("cx", node.x).attr("cy", node.y).attr("r", 22)
.attr("fill", fill)
.attr("stroke", isLeaf ? "#e91e63" : "#5a6fd6")
.attr("stroke-width", isLeaf ? 3 : 2);
g.append("text")
.attr("x", node.x).attr("y", node.y + 5)
.attr("text-anchor", "middle")
.attr("fill", "white").attr("font-weight", "bold").attr("font-size", "14px")
.text(node.val);
});
updateDisplays();
}
function updateDisplays() {
const pathContainer = document.getElementById('pathDisplay');
pathContainer.innerHTML = currentPath.length > 0
? currentPath.map(v => `<span style="background: #ffcc80; padding: 5px 12px; margin: 2px; border-radius: 15px; display: inline-block;">${v}</span>`).join(' → ')
: '<span style="color: #999;">(empty)</span>';
document.getElementById('sumDisplay').textContent = currentSum;
document.getElementById('sumDisplay').style.color =
currentSum === targetSum ? '#4caf50' : (currentSum > targetSum ? '#f44336' : '#2196f3');
}
function stepForward() {
if (stepIndex >= steps.length) return;
const step = steps[stepIndex];
currentPath = step.path || [];
currentSum = step.sum || 0;
if (step.type === 'found') {
successPath = step.path;
document.getElementById('resultDisplay').textContent = 'TRUE ✓';
document.getElementById('resultDisplay').style.color = '#4caf50';
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start DFS';
} else if (step.type === 'not_found') {
document.getElementById('resultDisplay').textContent = 'FALSE ✗';
document.getElementById('resultDisplay').style.color = '#f44336';
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start DFS';
}
document.getElementById('statusMessage').textContent = step.message;
stepIndex++;
render();
}
async function start() {
if (isRunning) {
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start DFS';
return;
}
isRunning = true;
document.getElementById('startBtn').textContent = '⏸ Pause';
while (stepIndex < steps.length && isRunning) {
stepForward();
await new Promise(r => setTimeout(r, 600));
}
}
function reset() {
targetSum = parseInt(document.getElementById('targetInput').value) || 22;
document.getElementById('targetDisplay').textContent = targetSum;
isRunning = false;
stepIndex = 0;
currentPath = [];
currentSum = 0;
successPath = [];
document.getElementById('statusMessage').textContent = 'Click Start to search for a path with target sum';
document.getElementById('resultDisplay').textContent = 'Searching...';
document.getElementById('resultDisplay').style.color = '#666';
document.getElementById('startBtn').textContent = '▶ Start DFS';
precomputeSteps();
render();
}
reset();
window.addEventListener('resize', render);
</script>
</body>
</html>