-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0226_invert_binary_tree.html
More file actions
513 lines (431 loc) · 17.2 KB
/
0226_invert_binary_tree.html
File metadata and controls
513 lines (431 loc) · 17.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 226: Invert Binary Tree - 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">#226</span> Invert Binary Tree</h1>
<p>Given the root of a binary tree, invert the tree (swap left and right children at every node), and return its root.</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Binary Tree</span>
<span class="meta-tag">🔄 Recursion</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(h) stack</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0226_invert_binary_tree/0226_invert_binary_tree.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Think of it like looking at a tree in a mirror:</p>
<ul>
<li><strong>At each node:</strong> Swap the left and right children</li>
<li><strong>Recursively:</strong> Do this for every node in the tree</li>
<li><strong>Order:</strong> We go deep first (post-order), then swap on the way back up</li>
<li><strong>Result:</strong> The entire tree is mirrored!</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="stepBtn" onclick="step()">Step</button>
<button class="btn btn-success" id="autoBtn" onclick="toggleAuto()">Auto Run</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="info-box secondary" style="margin-bottom: 20px;">
🌳 Input Tree: <strong>[4, 2, 7, 1, 3, 6, 9]</strong>
</div>
<div class="status-message" id="statusMessage">
Click "Step" or "Auto Run" to start visualization
</div>
<div style="display: flex; gap: 40px; justify-content: center; flex-wrap: wrap;">
<div>
<h4 style="text-align: center; margin-bottom: 10px;">Original Tree</h4>
<div id="originalTreeContainer" style="width: 350px; height: 300px; background: #f5f5f5; border-radius: 12px;"></div>
</div>
<div>
<h4 style="text-align: center; margin-bottom: 10px;">Current State</h4>
<div id="currentTreeContainer" style="width: 350px; height: 300px; background: #e8f5e9; border-radius: 12px;"></div>
</div>
</div>
<div class="explanation-panel" style="margin-top: 20px;">
<h4>📝 Recursion Stack</h4>
<div id="stackDisplay" style="display: flex; gap: 10px; flex-wrap: wrap; padding: 10px;">
<span style="color: #666;">Empty - Click Step to begin</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 226. Invert Binary Tree
Problem from LeetCode: https://leetcode.com/problems/invert-binary-tree/
Description:
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2:
Input: root = [2,1,3]
Output: [2,3,1]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invert_tree(self, root: TreeNode) ->TreeNode:
"""
Invert a binary tree.
Args:
root: Root node of the binary tree
Returns:
TreeNode: Root of the inverted binary tree
"""
if root is None:
return None
right = self.invert_tree(root.right)
left = self.invert_tree(root.left)
root.left = right
root.right = left
return root
def invert_tree_iterative(self, root: TreeNode) ->TreeNode:
"""
Invert a binary tree using an iterative approach (BFS).
Args:
root: Root node of the binary tree
Returns:
TreeNode: Root of the inverted binary tree
"""
if not root:
return None
queue = [root]
while queue:
current = queue.pop(0)
current.left, current.right = current.right, current.left
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return root
# Helper function to create a tree from a level-order traversal array
def create_tree(arr):
if not arr:
return None
root = TreeNode(arr[0])
queue = [root]
i = 1
while queue and i < len(arr):
node = queue.pop(0)
# Left child
if i < len(arr) and arr[i] is not None:
node.left = TreeNode(arr[i])
queue.append(node.left)
i += 1
# Right child
if i < len(arr) and arr[i] is not None:
node.right = TreeNode(arr[i])
queue.append(node.right)
i += 1
return root
# Helper function to convert a tree to a level-order traversal array
def tree_to_array(root):
if not root:
return []
result = []
queue = [root]
while queue:
node = queue.pop(0)
if node:
result.append(node.val)
queue.append(node.left)
queue.append(node.right)
else:
result.append(None)
# Remove trailing None values
while result and result[-1] is None:
result.pop()
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
arr1 = [4, 2, 7, 1, 3, 6, 9]
root1 = create_tree(arr1)
print(f"Example 1: root = {arr1}")
inverted1 = solution.invert_tree(root1)
result1 = tree_to_array(inverted1)
print(f"Output: {result1}") # Expected output: [4, 7, 2, 9, 6, 3, 1]
# Example 2
arr2 = [2, 1, 3]
root2 = create_tree(arr2)
print(f"\nExample 2: root = {arr2}")
inverted2 = solution.invert_tree(root2)
result2 = tree_to_array(inverted2)
print(f"Output: {result2}") # Expected output: [2, 3, 1]
# Example 3
arr3 = []
root3 = create_tree(arr3)
print(f"\nExample 3: root = {arr3}")
inverted3 = solution.invert_tree(root3)
result3 = tree_to_array(inverted3)
print(f"Output: {result3}") # Expected output: []
# Using iterative approach
print("\nUsing iterative approach:")
root1 = create_tree(arr1) # Reset the tree
inverted1_iter = solution.invert_tree_iterative(root1)
result1_iter = tree_to_array(inverted1_iter)
print(f"Example 1: {result1_iter}") # Expected output: [4, 7, 2, 9, 6, 3, 1]
</pre>
</div>
</div>
</div>
<script>
// Tree structure: [4, 2, 7, 1, 3, 6, 9]
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
const originalTree = {
val: 4,
left: {
val: 2,
left: { val: 1, left: null, right: null },
right: { val: 3, left: null, right: null }
},
right: {
val: 7,
left: { val: 6, left: null, right: null },
right: { val: 9, left: null, right: null }
}
};
let currentTree;
let steps = [];
let currentStepIdx = -1;
let autoInterval = null;
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
function generateSteps(node, path = []) {
if (node === null) return;
steps.push({
type: 'visit',
path: [...path],
val: node.val,
message: `Visiting node ${node.val}`
});
// Visit children first (post-order)
if (node.left) generateSteps(node.left, [...path, 'left']);
if (node.right) generateSteps(node.right, [...path, 'right']);
// Then swap
if (node.left || node.right) {
steps.push({
type: 'swap',
path: [...path],
val: node.val,
leftVal: node.left?.val || 'null',
rightVal: node.right?.val || 'null',
message: `Swapping children of node ${node.val}: ${node.left?.val || 'null'} ↔ ${node.right?.val || 'null'}`
});
}
}
function getNode(tree, path) {
let node = tree;
for (const dir of path) {
node = node[dir];
}
return node;
}
function swapChildren(tree, path) {
const node = getNode(tree, path);
const temp = node.left;
node.left = node.right;
node.right = temp;
}
function init() {
currentTree = deepCopy(originalTree);
steps = [];
generateSteps(originalTree);
renderTree('originalTreeContainer', originalTree, null, false);
renderTree('currentTreeContainer', currentTree, null, false);
}
function renderTree(containerId, tree, highlightPath, showSwap) {
const container = document.getElementById(containerId);
const width = container.offsetWidth;
const height = container.offsetHeight;
d3.select(`#${containerId}`).selectAll('*').remove();
const svg = d3.select(`#${containerId}`)
.append('svg')
.attr('width', width)
.attr('height', height);
const nodeRadius = 25;
const levelHeight = 70;
function getPositions(node, x, y, level, dx) {
if (!node) return [];
const positions = [{ node, x, y, level }];
const childDx = dx / 2;
if (node.left) {
positions.push(...getPositions(node.left, x - dx, y + levelHeight, level + 1, childDx));
}
if (node.right) {
positions.push(...getPositions(node.right, x + dx, y + levelHeight, level + 1, childDx));
}
return positions;
}
const positions = getPositions(tree, width / 2, 40, 0, 80);
const posMap = new Map();
positions.forEach(p => posMap.set(p.node, p));
// Draw edges
positions.forEach(({ node, x, y }) => {
if (node.left) {
const childPos = posMap.get(node.left);
svg.append('line')
.attr('x1', x)
.attr('y1', y + nodeRadius)
.attr('x2', childPos.x)
.attr('y2', childPos.y - nodeRadius)
.attr('stroke', '#999')
.attr('stroke-width', 2);
}
if (node.right) {
const childPos = posMap.get(node.right);
svg.append('line')
.attr('x1', x)
.attr('y1', y + nodeRadius)
.attr('x2', childPos.x)
.attr('y2', childPos.y - nodeRadius)
.attr('stroke', '#999')
.attr('stroke-width', 2);
}
});
// Draw nodes
positions.forEach(({ node, x, y }) => {
const g = svg.append('g')
.attr('transform', `translate(${x}, ${y})`);
let fillColor = '#fff';
let strokeColor = '#667eea';
// Check if this node is highlighted
if (highlightPath !== null) {
let testNode = tree;
let isMatch = true;
for (const dir of highlightPath) {
testNode = testNode[dir];
}
if (testNode === node) {
fillColor = showSwap ? '#ff9800' : '#4caf50';
strokeColor = showSwap ? '#e65100' : '#2e7d32';
}
}
g.append('circle')
.attr('r', nodeRadius)
.attr('fill', fillColor)
.attr('stroke', strokeColor)
.attr('stroke-width', 3);
g.append('text')
.attr('text-anchor', 'middle')
.attr('dy', 5)
.attr('font-size', '16px')
.attr('font-weight', 'bold')
.attr('fill', fillColor === '#fff' ? '#333' : '#fff')
.text(node.val);
});
}
function updateStackDisplay() {
const container = document.getElementById('stackDisplay');
if (currentStepIdx < 0) {
container.innerHTML = '<span style="color: #666;">Empty - Click Step to begin</span>';
return;
}
// Build stack from steps up to current
const stack = [];
for (let i = 0; i <= currentStepIdx; i++) {
const step = steps[i];
if (step.type === 'visit') {
stack.push(step.val);
} else if (step.type === 'swap') {
// Pop after swap (returning from recursion)
const idx = stack.lastIndexOf(step.val);
if (idx !== -1) stack.splice(idx, 1);
}
}
if (stack.length === 0) {
container.innerHTML = '<span style="color: #4caf50;">✅ Recursion complete!</span>';
return;
}
container.innerHTML = stack.map((val, i) =>
`<div style="padding: 5px 15px; background: ${i === stack.length - 1 ? '#667eea' : '#e0e0e0'};
color: ${i === stack.length - 1 ? 'white' : '#333'}; border-radius: 5px; font-weight: bold;">
${val}
</div>`
).join('');
}
function step() {
currentStepIdx++;
if (currentStepIdx >= steps.length) {
document.getElementById('statusMessage').className = 'status-message success';
document.getElementById('statusMessage').textContent = '✅ Tree inversion complete!';
document.getElementById('stepBtn').disabled = true;
stopAuto();
return;
}
const stepData = steps[currentStepIdx];
document.getElementById('statusMessage').textContent = stepData.message;
if (stepData.type === 'swap') {
swapChildren(currentTree, stepData.path);
renderTree('currentTreeContainer', currentTree, stepData.path, true);
} else {
renderTree('currentTreeContainer', currentTree, stepData.path, false);
}
updateStackDisplay();
}
function toggleAuto() {
if (autoInterval) {
stopAuto();
} else {
document.getElementById('autoBtn').textContent = 'Pause';
autoInterval = setInterval(() => {
if (currentStepIdx >= steps.length - 1) {
step();
stopAuto();
} else {
step();
}
}, 800);
}
}
function stopAuto() {
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById('autoBtn').textContent = 'Auto Run';
}
function reset() {
stopAuto();
currentStepIdx = -1;
document.getElementById('stepBtn').disabled = false;
document.getElementById('statusMessage').className = 'status-message';
document.getElementById('statusMessage').textContent = 'Click "Step" or "Auto Run" to start visualization';
init();
}
init();
</script>
</body>
</html>