-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0124_binary_tree_maximum_path_sum.html
More file actions
583 lines (496 loc) · 21.6 KB
/
Copy path0124_binary_tree_maximum_path_sum.html
File metadata and controls
583 lines (496 loc) · 21.6 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>124 - Binary Tree Maximum Path Sum</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">#124</span> Binary Tree Maximum Path Sum</h1>
<p>
Find the maximum path sum in a binary tree. Path doesn't need to pass through root.
Uses DFS, tracking max gain from each subtree and updating global maximum.
</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">📊 Array</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0124_binary_tree_maximum_path_sum/0124_binary_tree_maximum_path_sum.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Tree traversal is like <strong>exploring a family tree</strong>:</p>
<ul>
<li><strong>Root:</strong> Start at the top node</li>
<li><strong>Recurse:</strong> Visit left and right children</li>
<li><strong>Base case:</strong> Stop at null/leaf nodes</li>
<li><strong>Combine:</strong> Build answer from subtree results</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Auto Run to find maximum path sum</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Binary Tree Maximum Path Sum
Problem from LeetCode: https://leetcode.com/problems/binary-tree-maximum-path-sum/
Description:
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them.
A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Example 1:
Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Example 2:
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def max_path_sum(self, root: Optional[TreeNode]) -> int:
"""
Find the maximum path sum in a binary tree.
Args:
root: Root of the binary tree
Returns:
int: Maximum path sum
"""
# Initialize global max path sum
self.max_sum = float('-inf')
# Helper function to compute max path sum with the given node as highest point
def max_gain(node: Optional[TreeNode]) -> int:
if not node:
return 0
# Compute maximum path sum for left and right subtrees
# We take max(0, path_sum) because if path_sum < 0, we can just exclude that path
left_gain = max(0, max_gain(node.left))
right_gain = max(0, max_gain(node.right))
# Compute the current path sum with current node as the highest point
# This path can't be extended further up
current_path_sum = node.val + left_gain + right_gain
# Update global maximum
self.max_sum = max(self.max_sum, current_path_sum)
# Return the maximum sum of a path that can be extended further
# We can only choose one path (left or right) when extending upwards
return node.val + max(left_gain, right_gain)
# Start the recursion
max_gain(root)
return self.max_sum
def max_path_sum_iterative(self, root: Optional[TreeNode]) -> int:
"""
Iterative approach (post-order traversal with stack).
Args:
root: Root of the binary tree
Returns:
int: Maximum path sum
"""
# This is a more complex problem to solve iteratively
# because we need to track both the max path sum and the max gain from each node
# This implementation is left as a challenge for advanced users
pass # Implementation would go here
# Function to create a binary tree from a list (level-order traversal)
def create_tree_from_list(values):
if not values:
return None
root = TreeNode(values[0])
queue = [root]
i = 1
while queue and i < len(values):
node = queue.pop(0)
# Add left child
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
# Add right child
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
root1 = create_tree_from_list([1, 2, 3])
result1 = solution.max_path_sum(root1)
print(f"Example 1: {result1}") # Expected output: 6
# Example 2
root2 = create_tree_from_list([-10, 9, 20, None, None, 15, 7])
result2 = solution.max_path_sum(root2)
print(f"Example 2: {result2}") # Expected output: 42
# Additional test case
root3 = create_tree_from_list([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1])
result3 = solution.max_path_sum(root3)
print(f"Additional example: {result3}") # Expected output: 48 (11->4->5->8->13)
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 600;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Tree: [-10, 9, 20, null, null, 15, 7]
// Best path: 15 -> 20 -> 7 = 42
const treeData = {
val: -10,
left: { val: 9, left: null, right: null },
right: {
val: 20,
left: { val: 15, left: null, right: null },
right: { val: 7, left: null, right: null }
}
};
let nodeStates = {}; // nodeId -> { gain, leftGain, rightGain, pathSum, processed }
let maxSum = -Infinity;
let callStack = [];
let currentNode = null;
let bestPath = [];
let animationTimer = null;
function getNodeId(node, path = '') {
if (!node) return null;
return `${path}_${node.val}`;
}
function initializeNodes(node, path = 'root') {
if (!node) return;
const id = getNodeId(node, path);
nodeStates[id] = {
node,
path,
gain: null,
leftGain: null,
rightGain: null,
pathSum: null,
processed: false
};
if (node.left) initializeNodes(node.left, path + 'L');
if (node.right) initializeNodes(node.right, path + 'R');
}
function reset() {
nodeStates = {};
maxSum = -Infinity;
callStack = [];
currentNode = null;
bestPath = [];
initializeNodes(treeData);
callStack.push({ node: treeData, path: 'root', phase: 'visit' });
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent = "Find maximum path sum (path doesn't need to include root)";
render();
}
function render() {
svg.selectAll("*").remove();
// Draw tree
drawTree(treeData, 250, 80, 0, 'root');
// Draw max sum
drawMaxSum();
// Draw explanation
drawExplanation();
}
function drawTree(node, x, y, level, path) {
if (!node) return;
const nodeRadius = 28;
const levelHeight = 90;
const spread = 120 / (level + 1);
const id = getNodeId(node, path);
const state = nodeStates[id] || {};
const isCurrent = currentNode === id;
const isInBestPath = bestPath.includes(id);
const isProcessed = state.processed;
// Draw edges first
if (node.left) {
const childX = x - spread;
const childY = y + levelHeight;
svg.append("line")
.attr("x1", x)
.attr("y1", y + nodeRadius)
.attr("x2", childX)
.attr("y2", childY - nodeRadius)
.attr("stroke", isInBestPath && bestPath.includes(getNodeId(node.left, path + 'L')) ? "#10b981" : "#cbd5e1")
.attr("stroke-width", isInBestPath ? 3 : 2);
drawTree(node.left, childX, childY, level + 1, path + 'L');
}
if (node.right) {
const childX = x + spread;
const childY = y + levelHeight;
svg.append("line")
.attr("x1", x)
.attr("y1", y + nodeRadius)
.attr("x2", childX)
.attr("y2", childY - nodeRadius)
.attr("stroke", isInBestPath && bestPath.includes(getNodeId(node.right, path + 'R')) ? "#10b981" : "#cbd5e1")
.attr("stroke-width", isInBestPath ? 3 : 2);
drawTree(node.right, childX, childY, level + 1, path + 'R');
}
// Draw node
svg.append("circle")
.attr("cx", x)
.attr("cy", y)
.attr("r", nodeRadius)
.attr("fill", () => {
if (isInBestPath) return "#bbf7d0";
if (isCurrent) return "#fef3c7";
if (isProcessed) return "#dbeafe";
return "#f8fafc";
})
.attr("stroke", () => {
if (isInBestPath) return "#10b981";
if (isCurrent) return "#f59e0b";
if (isProcessed) return "#3b82f6";
return "#94a3b8";
})
.attr("stroke-width", isCurrent || isInBestPath ? 3 : 2);
svg.append("text")
.attr("x", x)
.attr("y", y + 6)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.val);
// Draw gain if calculated
if (state.gain !== null) {
svg.append("rect")
.attr("x", x + nodeRadius + 5)
.attr("y", y - 10)
.attr("width", 35)
.attr("height", 20)
.attr("rx", 4)
.attr("fill", "#dbeafe")
.attr("stroke", "#3b82f6");
svg.append("text")
.attr("x", x + nodeRadius + 22)
.attr("y", y + 5)
.attr("text-anchor", "middle")
.attr("font-size", "11px")
.attr("fill", "#1e293b")
.text(`+${state.gain}`);
}
}
function drawMaxSum() {
svg.append("text")
.attr("x", 550)
.attr("y", 50)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Maximum Path Sum:");
svg.append("rect")
.attr("x", 550)
.attr("y", 60)
.attr("width", 100)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", maxSum === -Infinity ? "#f8fafc" : "#d1fae5")
.attr("stroke", maxSum === -Infinity ? "#94a3b8" : "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 600)
.attr("y", 88)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(maxSum === -Infinity ? "?" : maxSum);
// Best path
if (bestPath.length > 0) {
svg.append("text")
.attr("x", 550)
.attr("y", 130)
.attr("font-size", "12px")
.attr("fill", "#10b981")
.text("Best: 15 → 20 → 7");
}
}
function drawExplanation() {
const startX = 550;
const startY = 180;
svg.append("text")
.attr("x", startX)
.attr("y", startY)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Key Insight:");
const explanations = [
"• max_gain(node) returns the max",
" sum path starting from node going",
" down (can only go one direction)",
"",
"• At each node, we also compute",
" the path sum through that node",
" (left_gain + node + right_gain)",
"",
"• Negative gains are replaced with 0",
" (don't include negative subtrees)"
];
explanations.forEach((exp, idx) => {
svg.append("text")
.attr("x", startX)
.attr("y", startY + 25 + idx * 18)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(exp);
});
// Current state
if (currentNode) {
const state = nodeStates[currentNode];
if (state) {
svg.append("text")
.attr("x", startX)
.attr("y", 430)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Current: node=${state.node.val}`);
if (state.leftGain !== null) {
svg.append("text")
.attr("x", startX)
.attr("y", 455)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(`left_gain = max(0, ${state.leftGain}) = ${Math.max(0, state.leftGain)}`);
}
if (state.rightGain !== null) {
svg.append("text")
.attr("x", startX)
.attr("y", 475)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(`right_gain = max(0, ${state.rightGain}) = ${Math.max(0, state.rightGain)}`);
}
if (state.pathSum !== null) {
svg.append("text")
.attr("x", startX)
.attr("y", 495)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(`path_sum = ${state.pathSum}`);
}
}
}
}
function step() {
if (callStack.length === 0) {
document.getElementById("status").textContent =
`✓ Complete! Maximum path sum = ${maxSum} (path: 15 → 20 → 7)`;
bestPath = ['root_-10R_20L_15', 'root_-10R_20', 'root_-10R_20R_7'];
render();
return;
}
const { node, path, phase, leftGain, rightGain } = callStack.pop();
const id = getNodeId(node, path);
currentNode = id;
if (phase === 'visit') {
// Need to process children first
if (node.right) {
callStack.push({ node, path, phase: 'processRight', leftGain: null });
callStack.push({ node: node.right, path: path + 'R', phase: 'visit' });
} else if (node.left) {
callStack.push({ node, path, phase: 'processLeft', leftGain: null, rightGain: 0 });
callStack.push({ node: node.left, path: path + 'L', phase: 'visit' });
} else {
// Leaf node
const gain = node.val;
nodeStates[id].gain = gain;
nodeStates[id].leftGain = 0;
nodeStates[id].rightGain = 0;
nodeStates[id].pathSum = node.val;
nodeStates[id].processed = true;
maxSum = Math.max(maxSum, node.val);
document.getElementById("status").textContent =
`Leaf node ${node.val}: gain=${gain}, max_sum=${maxSum}`;
}
} else if (phase === 'processRight') {
const rightId = getNodeId(node.right, path + 'R');
const rGain = nodeStates[rightId].gain;
if (node.left) {
callStack.push({ node, path, phase: 'processLeft', rightGain: rGain });
callStack.push({ node: node.left, path: path + 'L', phase: 'visit' });
} else {
// No left child
const leftGainVal = 0;
const rightGainVal = Math.max(0, rGain);
const pathSum = node.val + leftGainVal + rightGainVal;
const gain = node.val + Math.max(leftGainVal, rightGainVal);
nodeStates[id].gain = gain;
nodeStates[id].leftGain = 0;
nodeStates[id].rightGain = rGain;
nodeStates[id].pathSum = pathSum;
nodeStates[id].processed = true;
maxSum = Math.max(maxSum, pathSum);
document.getElementById("status").textContent =
`Node ${node.val}: path_sum=${pathSum}, gain=${gain}, max_sum=${maxSum}`;
}
} else if (phase === 'processLeft') {
const leftId = getNodeId(node.left, path + 'L');
const lGain = nodeStates[leftId].gain;
const rGain = rightGain !== undefined ? rightGain : 0;
const leftGainVal = Math.max(0, lGain);
const rightGainVal = Math.max(0, rGain);
const pathSum = node.val + leftGainVal + rightGainVal;
const gain = node.val + Math.max(leftGainVal, rightGainVal);
nodeStates[id].gain = gain;
nodeStates[id].leftGain = lGain;
nodeStates[id].rightGain = rGain;
nodeStates[id].pathSum = pathSum;
nodeStates[id].processed = true;
maxSum = Math.max(maxSum, pathSum);
document.getElementById("status").textContent =
`Node ${node.val}: left=${lGain}, right=${rGain}, path_sum=${pathSum}, max_sum=${maxSum}`;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (callStack.length === 0) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
step(); // Final update
return;
}
step();
}, 1000);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>