-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0297_serialize_and_deserialize_binary_tree.html
More file actions
493 lines (413 loc) · 16.3 KB
/
0297_serialize_and_deserialize_binary_tree.html
File metadata and controls
493 lines (413 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>297 - Serialize and Deserialize Binary Tree</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">#297</span> Serialize and Deserialize Binary Tree</h1>
<p>
Design an algorithm to serialize a binary tree to a string, and deserialize
that string back to the original tree structure. Uses preorder traversal.
</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/0297_serialize_and_deserialize_binary_tree/0297_serialize_and_deserialize_binary_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>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="serializeBtn" class="btn">Serialize</button>
<button id="deserializeBtn" class="btn btn-success">Deserialize</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Click Serialize to convert tree to string</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
from collections import deque
"""
LeetCode 297: Serialize and Deserialize Binary Tree
Problem from LeetCode: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
Serialization is the process of converting a data structure or object into a sequence of bits so that
it can be stored in a file or memory buffer, or transmitted across a network connection link to be
reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your
serialization/deserialization algorithm should work. You just need to ensure that a binary tree can
be serialized to a string and this string can be deserialized to the original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do
not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 10^4]
- -1000 <= Node.val <= 1000
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Codec:
"""
Serializes and deserializes a binary tree.
Uses a preorder traversal approach with comma-separated values.
"""
def serialize(self, root: Optional[TreeNode]) ->str:
"""
Encodes a tree to a single string.
Args:
root: Root of the binary tree
Returns:
str: Serialized string representation of the tree
"""
result = []
def dfs(node):
if not node:
result.append('None')
return
result.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(result)
def deserialize(self, data: str) ->Optional[TreeNode]:
"""
Decodes your encoded data to tree.
Args:
data: Serialized string representation of the tree
Returns:
TreeNode: Root of the reconstructed binary tree
"""
values = data.split(',')
self.i = 0
def dfs():
if self.i >= len(values) or values[self.i] == 'None':
self.i += 1
return None
node = TreeNode(int(values[self.i]))
self.i += 1
node.left = dfs()
node.right = dfs()
return node
return dfs()
class CodecAlternative:
"""
Alternative implementation using list processing.
"""
def serialize(self, root: Optional[TreeNode]) ->str:
"""
Encodes a tree to a single string.
Args:
root: Root of the binary tree
Returns:
str: Serialized string representation of the tree
"""
def recserialize(root, string):
if not root:
string += 'None,'
else:
string += str(root.val) + ','
string = recserialize(root.left, string)
string = recserialize(root.right, string)
return string
return recserialize(root, '')
def deserialize(self, data: str) ->Optional[TreeNode]:
"""
Decodes your encoded data to tree.
Args:
data: Serialized string representation of the tree
Returns:
TreeNode: Root of the reconstructed binary tree
"""
def recdeserialize(string_deque):
if string_deque[0] == 'None':
string_deque.popleft()
return None
root = TreeNode(int(string_deque[0]))
string_deque.popleft()
root.left = recdeserialize(string_deque)
root.right = recdeserialize(string_deque)
return root
string_list = data.split(',')
if string_list[-1] == '':
string_list.pop()
string_deque = deque(string_list)
return recdeserialize(string_deque)
if __name__ == '__main__':
# Example usage based on LeetCode sample
# Create a sample tree: [1,2,3,null,null,4,5]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
codec = Codec()
# Serialize the tree
serialized = codec.serialize(root)
print(f"Serialized tree: {serialized}")
# Deserialize back to a tree
deserialized_root = codec.deserialize(serialized)
# Verify by serializing again
serialized_again = codec.serialize(deserialized_root)
print(f"Serialized again: {serialized_again}")
# Verify both serializations match
print(f"Serializations match: {serialized == serialized_again}")
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 600;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Sample tree
const originalTree = {
val: 1,
left: { val: 2, left: null, right: null },
right: {
val: 3,
left: { val: 4, left: null, right: null },
right: { val: 5, left: null, right: null }
}
};
let mode = "tree";
let serializedStr = "";
let currentNode = null;
let traversalOrder = [];
let traversalIdx = 0;
let deserializedTree = null;
function reset() {
mode = "tree";
serializedStr = "";
currentNode = null;
traversalOrder = [];
traversalIdx = 0;
deserializedTree = null;
document.getElementById("status").textContent = "Click Serialize to convert tree to string";
render();
}
function getTreeNodes(node, x, y, level, side) {
if (!node) return [];
const spacing = 180 / (level + 1);
const nodes = [{
val: node.val,
x: x,
y: y,
left: node.left,
right: node.right
}];
if (node.left) {
nodes.push(...getTreeNodes(node.left, x - spacing, y + 70, level + 1, 'left'));
}
if (node.right) {
nodes.push(...getTreeNodes(node.right, x + spacing, y + 70, level + 1, 'right'));
}
return nodes;
}
function preorderTraversal(node, result = []) {
if (!node) {
result.push("None");
return result;
}
result.push(String(node.val));
preorderTraversal(node.left, result);
preorderTraversal(node.right, result);
return result;
}
function render() {
svg.selectAll("*").remove();
if (mode === "tree" || mode === "serializing") {
drawTree(originalTree, 250, 100, "Original Tree");
}
if (mode === "serialized" || mode === "deserializing") {
drawSerializedString();
}
if (mode === "deserialized") {
drawTree(deserializedTree, 650, 100, "Reconstructed Tree");
drawSerializedString();
}
}
function drawTree(tree, startX, startY, title) {
svg.append("text")
.attr("x", startX)
.attr("y", startY - 30)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(title);
const nodes = getTreeNodes(tree, startX, startY, 0);
// Draw edges
function drawEdges(node, x, y, level) {
if (!node) return;
const spacing = 180 / (level + 1);
if (node.left) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x - spacing)
.attr("y2", y + 70)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
drawEdges(node.left, x - spacing, y + 70, level + 1);
}
if (node.right) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x + spacing)
.attr("y2", y + 70)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
drawEdges(node.right, x + spacing, y + 70, level + 1);
}
}
drawEdges(tree, startX, startY, 0);
// Draw nodes
nodes.forEach(node => {
const isHighlighted = currentNode && currentNode.val === node.val;
svg.append("circle")
.attr("cx", node.x)
.attr("cy", node.y)
.attr("r", 25)
.attr("fill", isHighlighted ? "#fef3c7" : "#dbeafe")
.attr("stroke", isHighlighted ? "#f59e0b" : "#3b82f6")
.attr("stroke-width", isHighlighted ? 3 : 2);
svg.append("text")
.attr("x", node.x)
.attr("y", node.y + 6)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.val);
});
}
function drawSerializedString() {
const y = 400;
const values = serializedStr.split(",");
svg.append("text")
.attr("x", 50)
.attr("y", y - 20)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Serialized String (Preorder Traversal):");
values.forEach((val, idx) => {
const x = 60 + idx * 70;
const isNull = val === "None";
const isActive = idx === traversalIdx && mode === "deserializing";
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 60)
.attr("height", 35)
.attr("rx", 6)
.attr("fill", () => {
if (isActive) return "#fef3c7";
if (isNull) return "#f1f5f9";
return "#d1fae5";
})
.attr("stroke", () => {
if (isActive) return "#f59e0b";
if (isNull) return "#94a3b8";
return "#10b981";
})
.attr("stroke-width", isActive ? 2 : 1);
svg.append("text")
.attr("x", x + 30)
.attr("y", y + 23)
.attr("text-anchor", "middle")
.attr("font-size", isNull ? "11px" : "14px")
.attr("font-weight", "bold")
.attr("fill", isNull ? "#64748b" : "#1e293b")
.text(val);
svg.append("text")
.attr("x", x + 30)
.attr("y", y + 55)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#94a3b8")
.text(idx);
});
// Explanation
svg.append("text")
.attr("x", 50)
.attr("y", y + 90)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Preorder: Visit node → process left subtree → process right subtree");
svg.append("text")
.attr("x", 50)
.attr("y", y + 110)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("None markers indicate null children, essential for reconstruction");
}
function serialize() {
traversalOrder = preorderTraversal(originalTree);
serializedStr = traversalOrder.join(",");
mode = "serialized";
document.getElementById("status").textContent =
`Serialized: "${serializedStr}" (${traversalOrder.length} values)`;
render();
}
function deserialize() {
if (!serializedStr) {
serialize();
}
// Reconstruct tree from serialized string
const values = serializedStr.split(",");
let idx = 0;
function buildTree() {
if (idx >= values.length) return null;
const val = values[idx++];
if (val === "None") return null;
return {
val: parseInt(val),
left: buildTree(),
right: buildTree()
};
}
deserializedTree = buildTree();
mode = "deserialized";
document.getElementById("status").textContent =
"✓ Deserialized! Tree reconstructed from string.";
render();
}
document.getElementById("serializeBtn").addEventListener("click", serialize);
document.getElementById("deserializeBtn").addEventListener("click", deserialize);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>