-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0572_subtree_of_another_tree.html
More file actions
551 lines (469 loc) · 20.2 KB
/
Copy path0572_subtree_of_another_tree.html
File metadata and controls
551 lines (469 loc) · 20.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Subtree of Another Tree - LeetCode 572</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">#0572</span> Subtree of Another Tree</h1>
<p><strong>Problem:</strong> Check if a tree is a subtree of another tree. A subtree includes the node and all its descendants.</p>
<p><strong>Pattern:</strong> DFS + Tree Comparison - For each node, check if it matches the subtree</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/0572_subtree_of_another_tree/0572_subtree_of_another_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 check if subRoot is a subtree</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Main Tree Node:</span>
<span id="mainNodeDisplay">-</span>
</div>
<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 Subtree of Another Tree
Problem from LeetCode: https://leetcode.com/problems/subtree-of-another-tree/
Description:
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values as subRoot and false otherwise.
A subtree of a binary tree is a tree that consists of a node in the original tree and all of this node's descendants.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,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_subtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]
) ->bool:
"""
Check if subRoot is a subtree of root.
Args:
root: Root of the main tree
subRoot: Root of the potential subtree
Returns:
bool: True if subRoot is a subtree of root, False otherwise
"""
if not root:
return False
if self._isSameTree(root, subRoot):
return True
return self.is_subtree(root.left, subRoot) or self.is_subtree(root.right, subRoot)
def _isSameTree(self, s: Optional[TreeNode], t: Optional[TreeNode]) ->bool:
"""
Check if two trees are identical.
Args:
s: Root of the first tree
t: Root of the second tree
Returns:
bool: True if the trees are identical, False otherwise
"""
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
return False
return self._isSameTree(s.left, t.left) and self._isSameTree(s.
right, t.right)
def isSubtree_serialize(self, root: Optional[TreeNode], subRoot:
Optional[TreeNode]) ->bool:
"""
Check if subRoot is a subtree of root using serialization.
Args:
root: Root of the main tree
subRoot: Root of the potential subtree
Returns:
bool: True if subRoot is a subtree of root, False otherwise
"""
def serialize(node: Optional[TreeNode]) ->str:
"""Serialize a tree to a string."""
if not node:
return '#'
return f',{node.val}{serialize(node.left)}{serialize(node.right)}'
return serialize(subRoot) in serialize(root)
def isSubtree_efficient(self, root: Optional[TreeNode], subRoot:
Optional[TreeNode]) ->bool:
"""
More efficient implementation avoiding redundant comparisons.
Args:
root: Root of the main tree
subRoot: Root of the potential subtree
Returns:
bool: True if subRoot is a subtree of root, False otherwise
"""
if not subRoot:
return True
if not root:
return False
def dfs_find(node: Optional[TreeNode], target: int) ->list:
"""Find all nodes with the value equal to target."""
if not node:
return []
result = []
if node.val == target:
result.append(node)
result.extend(dfs_find(node.left, target))
result.extend(dfs_find(node.right, target))
return result
candidates = dfs_find(root, subRoot.val)
for candidate in candidates:
if self._isSameTree(candidate, subRoot):
return True
return False
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1: Create the main tree [3,4,5,1,2]
root1 = TreeNode(3)
root1.left = TreeNode(4)
root1.right = TreeNode(5)
root1.left.left = TreeNode(1)
root1.left.right = TreeNode(2)
# Create the subtree [4,1,2]
subRoot1 = TreeNode(4)
subRoot1.left = TreeNode(1)
subRoot1.right = TreeNode(2)
result1 = solution.is_subtree(root1, subRoot1)
print(f"Example 1: {result1}") # Expected output: True
# Example 2: Create the main tree [3,4,5,1,2,null,null,null,null,0]
root2 = TreeNode(3)
root2.left = TreeNode(4)
root2.right = TreeNode(5)
root2.left.left = TreeNode(1)
root2.left.right = TreeNode(2)
root2.left.right.left = TreeNode(0)
# Use the same subtree [4,1,2]
result2 = solution.is_subtree(root2, subRoot1)
print(f"Example 2: {result2}") # Expected output: False
</pre>
</div>
</div>
</div>
<script>
// Main tree
const mainTree = {
val: 3,
left: {
val: 4,
left: {val: 1, left: null, right: null},
right: {val: 2, left: null, right: null}
},
right: {val: 5, left: null, right: null}
};
// Subtree to find
const subTree = {
val: 4,
left: {val: 1, left: null, right: null},
right: {val: 2, left: null, right: null}
};
let nodeStates = {}; // path -> 'checking' | 'match' | 'nomatch' | 'found'
let compareStates = {}; // 'sub_path' -> 'comparing' | 'match' | 'nomatch'
let callStack = [{type: 'main', node: mainTree, path: 'root'}];
let foundSubtree = false;
let currentCompare = null;
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 400;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function drawTree(node, x, y, level, path, isSubtree, statesMap) {
if (!node) return;
const nodeRadius = 22;
const dx = isSubtree ? 45 / (level + 1) : 80 / (level + 1);
const dy = isSubtree ? 50 : 60;
// Edges
if (node.left) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x - dx).attr("y2", y + dy - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawTree(node.left, x - dx, y + dy, level + 1, path + 'L', isSubtree, statesMap);
}
if (node.right) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x + dx).attr("y2", y + dy - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawTree(node.right, x + dx, y + dy, level + 1, path + 'R', isSubtree, statesMap);
}
// Node
const state = statesMap[path];
let fill = "#e3f2fd", stroke = "#1976d2";
if (state === 'checking' || state === 'comparing') {
fill = "#ffeb3b"; stroke = "#f57c00";
} else if (state === 'match') {
fill = "#c8e6c9"; stroke = "#4caf50";
} else if (state === 'nomatch') {
fill = "#ffcdd2"; stroke = "#e53935";
} else if (state === 'found') {
fill = "#b39ddb"; stroke = "#673ab7";
}
svg.append("circle")
.attr("cx", x).attr("cy", y).attr("r", nodeRadius)
.attr("fill", fill).attr("stroke", stroke).attr("stroke-width", 2);
svg.append("text")
.attr("x", x).attr("y", y + 5)
.attr("text-anchor", "middle")
.attr("font-size", isSubtree ? "14px" : "16px")
.attr("font-weight", "bold")
.text(node.val);
}
function draw() {
svg.selectAll("*").remove();
// Main tree label
svg.append("text")
.attr("x", 200).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("Main Tree (root)");
// Subtree label
svg.append("text")
.attr("x", 620).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text("SubRoot");
// Draw main tree
drawTree(mainTree, 200, 80, 0, 'root', false, nodeStates);
// Draw subtree
drawTree(subTree, 620, 80, 0, 'sub', true, compareStates);
// Divider
svg.append("line")
.attr("x1", 430).attr("y1", 40)
.attr("x2", 430).attr("y2", height - 40)
.attr("stroke", "#ddd").attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5");
// Legend
const legend = [
{color: "#e3f2fd", label: "Not checked"},
{color: "#ffeb3b", label: "Checking"},
{color: "#c8e6c9", label: "Match"},
{color: "#ffcdd2", label: "No match"},
{color: "#b39ddb", label: "Subtree found"}
];
legend.forEach((item, i) => {
svg.append("rect")
.attr("x", 10 + i * 110).attr("y", height - 30)
.attr("width", 15).attr("height", 15)
.attr("fill", item.color)
.attr("stroke", "#999");
svg.append("text")
.attr("x", 30 + i * 110).attr("y", height - 18)
.attr("font-size", "10px")
.text(item.label);
});
// Result
if (foundSubtree) {
svg.append("rect")
.attr("x", width / 2 - 80).attr("y", height - 70)
.attr("width", 160).attr("height", 35)
.attr("rx", 8)
.attr("fill", "#c8e6c9").attr("stroke", "#4caf50");
svg.append("text")
.attr("x", width / 2).attr("y", height - 46)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.text("✓ Subtree Found!");
}
}
function getNode(tree, path) {
let node = tree;
for (let c of path.slice(4)) { // skip 'root' or 'sub_'
if (!node) return null;
node = c === 'L' ? node.left : node.right;
}
return node;
}
function step() {
if (foundSubtree || callStack.length === 0) {
if (!foundSubtree && callStack.length === 0) {
document.getElementById("status").textContent = "Subtree NOT found!";
document.getElementById("resultDisplay").textContent = "Not Found";
}
draw();
return false;
}
const task = callStack.pop();
if (task.type === 'main') {
// Check this main tree node as potential subtree root
const {node, path} = task;
if (!node) return callStack.length > 0;
nodeStates[path] = 'checking';
document.getElementById("mainNodeDisplay").textContent = `Node ${node.val}`;
// Start comparison with subtree
callStack.push({type: 'main_done', path});
callStack.push({type: 'compare', mainPath: path, subPath: 'sub', mainNode: node, subNode: subTree});
document.getElementById("status").textContent =
`Checking if subtree rooted at ${node.val} matches subRoot...`;
} else if (task.type === 'compare') {
const {mainPath, subPath, mainNode, subNode} = task;
// Both null = match
if (!mainNode && !subNode) {
compareStates[subPath] = 'match';
return callStack.length > 0;
}
// One null = no match
if (!mainNode || !subNode) {
compareStates[subPath] = 'nomatch';
return callStack.length > 0;
}
compareStates[subPath] = 'comparing';
document.getElementById("compareDisplay").textContent =
`Main(${mainNode.val}) vs Sub(${subNode.val})`;
if (mainNode.val !== subNode.val) {
compareStates[subPath] = 'nomatch';
document.getElementById("status").textContent =
`${mainNode.val} ≠ ${subNode.val} - no match`;
} else {
// Values match, check children
callStack.push({type: 'compare_done', subPath});
callStack.push({
type: 'compare',
mainPath: mainPath + 'R',
subPath: subPath + 'R',
mainNode: mainNode.right,
subNode: subNode.right
});
callStack.push({
type: 'compare',
mainPath: mainPath + 'L',
subPath: subPath + 'L',
mainNode: mainNode.left,
subNode: subNode.left
});
document.getElementById("status").textContent =
`${mainNode.val} = ${subNode.val} ✓ - checking children...`;
}
} else if (task.type === 'compare_done') {
const {subPath} = task;
const leftMatch = compareStates[subPath + 'L'] === 'match' ||
!getNode(subTree, subPath.slice(3) + 'L');
const rightMatch = compareStates[subPath + 'R'] === 'match' ||
!getNode(subTree, subPath.slice(3) + 'R');
if (leftMatch && rightMatch) {
compareStates[subPath] = 'match';
} else {
compareStates[subPath] = 'nomatch';
}
} else if (task.type === 'main_done') {
const {path} = task;
const matched = compareStates['sub'] === 'match';
if (matched) {
nodeStates[path] = 'found';
foundSubtree = true;
document.getElementById("status").textContent =
`Found subtree at node ${getNode(mainTree, path).val}!`;
document.getElementById("resultDisplay").textContent = "Found!";
} else {
nodeStates[path] = 'nomatch';
// Reset compare states and try children
compareStates = {};
const node = getNode(mainTree, path);
if (node) {
if (node.right) {
callStack.push({type: 'main', node: node.right, path: path + 'R'});
}
if (node.left) {
callStack.push({type: 'main', node: node.left, path: path + 'L'});
}
}
document.getElementById("status").textContent =
`No match at ${node?.val}, trying other nodes...`;
}
}
draw();
return callStack.length > 0 && !foundSubtree;
}
function reset() {
nodeStates = {};
compareStates = {};
callStack = [{type: 'main', node: mainTree, path: 'root'}];
foundSubtree = false;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("mainNodeDisplay").textContent = "-";
document.getElementById("compareDisplay").textContent = "-";
document.getElementById("resultDisplay").textContent = "-";
document.getElementById("status").textContent =
'Click "Step" to check if subRoot is a subtree';
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>