-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0100_same_tree.html
More file actions
475 lines (400 loc) · 16.3 KB
/
0100_same_tree.html
File metadata and controls
475 lines (400 loc) · 16.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Same Tree - LeetCode 100</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">#0100</span> Same Tree</h1>
<p><strong>Problem:</strong> Given the roots of two binary trees, check if they are the same or not. Two trees are the same if they are structurally identical and have the same node values.</p>
<p><strong>Pattern:</strong> DFS/Recursion - Compare nodes simultaneously</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0100_same_tree/0100_same_tree.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>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" to compare trees node by node</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Comparing:</span>
<span id="compareDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Result:</span>
<span id="resultDisplay">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Same Tree
Problem from LeetCode: https://leetcode.com/problems/same-tree/
Description:
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_same_tree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are the same (recursive approach).
Args:
p: Root of the first binary tree
q: Root of the second binary tree
Returns:
bool: True if the trees are the same, False otherwise
"""
# If both nodes are None, they are the same
if not p and not q:
return True
# If one is None but the other isn't, they are different
if not p or not q:
return False
# Check if values are the same and recursively check subtrees
return (p.val == q.val and
self.is_same_tree(p.left, q.left) and
self.is_same_tree(p.right, q.right))
def is_same_tree_iterative(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are the same (iterative approach).
Args:
p: Root of the first binary tree
q: Root of the second binary tree
Returns:
bool: True if the trees are the same, False otherwise
"""
# Queue for BFS traversal of both trees
queue = [(p, q)]
while queue:
node1, node2 = queue.pop(0)
# If both nodes are None, continue to next pair
if not node1 and not node2:
continue
# If one is None but the other isn't, they are different
if not node1 or not node2:
return False
# If values are different, they are different trees
if node1.val != node2.val:
return False
# Add children to the queue
queue.append((node1.left, node2.left))
queue.append((node1.right, node2.right))
return True
def is_same_tree_preorder(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
"""
Check if two binary trees are the same using preorder traversal.
Args:
p: Root of the first binary tree
q: Root of the second binary tree
Returns:
bool: True if the trees are the same, False otherwise
"""
def preorder(node):
if not node:
return [None]
return [node.val] + preorder(node.left) + preorder(node.right)
return preorder(p) == preorder(q)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
# Tree p: Tree q:
# 1 1
# / \ / \
# 2 3 2 3
p1 = TreeNode(1, TreeNode(2), TreeNode(3))
q1 = TreeNode(1, TreeNode(2), TreeNode(3))
result1 = solution.is_same_tree(p1, q1)
print(f"Example 1: {result1}") # Expected output: True
# Example 2
# Tree p: Tree q:
# 1 1
# / \
# 2 2
p2 = TreeNode(1, TreeNode(2))
q2 = TreeNode(1, None, TreeNode(2))
result2 = solution.is_same_tree(p2, q2)
print(f"Example 2: {result2}") # Expected output: False
# Example 3
# Tree p: Tree q:
# 1 1
# / \ / \
# 2 1 1 2
p3 = TreeNode(1, TreeNode(2), TreeNode(1))
q3 = TreeNode(1, TreeNode(1), TreeNode(2))
result3 = solution.is_same_tree(p3, q3)
print(f"Example 3: {result3}") # Expected output: False
# Compare with other implementations
print("\nUsing iterative approach:")
print(f"Example 1: {solution.is_same_tree_iterative(p1, q1)}")
print(f"Example 2: {solution.is_same_tree_iterative(p2, q2)}")
print(f"Example 3: {solution.is_same_tree_iterative(p3, q3)}")
print("\nUsing preorder traversal approach:")
print(f"Example 1: {solution.is_same_tree_preorder(p1, q1)}")
print(f"Example 2: {solution.is_same_tree_preorder(p2, q2)}")
print(f"Example 3: {solution.is_same_tree_preorder(p3, q3)}")
</pre>
</div>
</div>
</div>
<script>
// Tree structure: [value, left, right] or null
const tree1 = {val: 1, left: {val: 2, left: null, right: null}, right: {val: 3, left: null, right: null}};
const tree2 = {val: 1, left: {val: 2, left: null, right: null}, right: {val: 3, left: null, right: null}};
let stack = [[tree1, tree2, "root"]];
let compared = [];
let result = null;
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 350;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function drawTree(tree, x, y, level, side, highlight, treeNum) {
if (!tree) return;
const nodeRadius = 25;
const dx = 80 / (level + 1);
const dy = 60;
// Draw edges first
if (tree.left) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x - dx)
.attr("y2", y + dy)
.attr("stroke", "#ddd")
.attr("stroke-width", 2);
}
if (tree.right) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x + dx)
.attr("y2", y + dy)
.attr("stroke", "#ddd")
.attr("stroke-width", 2);
}
// Node
const nodePath = side;
const isHighlight = highlight === nodePath;
const wasCompared = compared.includes(nodePath);
svg.append("circle")
.attr("cx", x)
.attr("cy", y)
.attr("r", nodeRadius)
.attr("fill", isHighlight ? "#ffeb3b" :
wasCompared ? "#c8e6c9" : "#e3f2fd")
.attr("stroke", isHighlight ? "#f57c00" :
wasCompared ? "#4caf50" : "#1976d2")
.attr("stroke-width", isHighlight ? 3 : 2);
svg.append("text")
.attr("x", x)
.attr("y", y + 5)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.text(tree.val);
// Recurse
if (tree.left) {
drawTree(tree.left, x - dx, y + dy, level + 1, side + "L", highlight, treeNum);
}
if (tree.right) {
drawTree(tree.right, x + dx, y + dy, level + 1, side + "R", highlight, treeNum);
}
}
function draw(currentPath = null) {
svg.selectAll("*").remove();
// Labels
svg.append("text")
.attr("x", 200)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Tree p");
svg.append("text")
.attr("x", 600)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Tree q");
// Draw trees
drawTree(tree1, 200, 80, 0, "root", currentPath, 1);
drawTree(tree2, 600, 80, 0, "root", currentPath, 2);
// Comparison indicator
if (currentPath) {
svg.append("text")
.attr("x", 400)
.attr("y", 150)
.attr("text-anchor", "middle")
.attr("font-size", "30px")
.text("⟺");
}
// Result display
if (result !== null) {
svg.append("rect")
.attr("x", 300)
.attr("y", 280)
.attr("width", 200)
.attr("height", 50)
.attr("rx", 10)
.attr("fill", result ? "#c8e6c9" : "#ffcdd2")
.attr("stroke", result ? "#4caf50" : "#e53935")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 400)
.attr("y", 310)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(result ? "✓ Same Tree" : "✗ Different");
}
}
function getNode(tree, path) {
if (!tree) return null;
if (path === "root") return tree;
let node = tree;
for (let i = 4; i < path.length; i++) {
if (!node) return null;
node = path[i] === 'L' ? node.left : node.right;
}
return node;
}
function step() {
if (stack.length === 0 || result === false) {
if (result === null) result = true;
document.getElementById("status").textContent =
result ? "Trees are the same!" : "Trees are different!";
document.getElementById("resultDisplay").textContent =
result ? "Same ✓" : "Different ✗";
draw();
return false;
}
const [p, q, path] = stack.pop();
// Both null - same for this subtree
if (!p && !q) {
document.getElementById("compareDisplay").textContent = `${path}: both null ✓`;
document.getElementById("status").textContent =
`Comparing ${path}: both null - same`;
compared.push(path);
draw(path);
return stack.length > 0;
}
// One null, one not
if (!p || !q) {
result = false;
document.getElementById("compareDisplay").textContent =
`${path}: one null, one not ✗`;
document.getElementById("status").textContent =
`Comparing ${path}: structure mismatch!`;
draw(path);
return false;
}
// Compare values
if (p.val !== q.val) {
result = false;
document.getElementById("compareDisplay").textContent =
`${path}: ${p.val} ≠ ${q.val} ✗`;
document.getElementById("status").textContent =
`Comparing ${path}: values differ (${p.val} vs ${q.val})`;
draw(path);
return false;
}
// Values match, add children to stack
document.getElementById("compareDisplay").textContent =
`${path}: ${p.val} = ${q.val} ✓`;
document.getElementById("status").textContent =
`Comparing ${path}: ${p.val} = ${q.val} - match!`;
compared.push(path);
// Add right first so left is processed first (stack is LIFO)
stack.push([p.right, q.right, path + "R"]);
stack.push([p.left, q.left, path + "L"]);
draw(path);
return true;
}
function reset() {
stack = [[tree1, tree2, "root"]];
compared = [];
result = null;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("compareDisplay").textContent = "-";
document.getElementById("resultDisplay").textContent = "-";
document.getElementById("status").textContent =
'Click "Step" to compare trees node by node';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>