-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize-deserialize.ts
More file actions
53 lines (47 loc) · 1.39 KB
/
Copy pathserialize-deserialize.ts
File metadata and controls
53 lines (47 loc) · 1.39 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
import { TreeNode } from "../lib/tree-node.js";
/**
* 297. Serialize and Deserialize Binary Tree (Hard)
* Link: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
*
* Design algorithms to serialize a binary tree to a string and deserialize that
* string back to an identical tree.
*
* Example:
* serialize([1,2,3,null,null,4,5]) -> "1,2,#,#,3,4,#,#,5,#,#"
* deserialize(...) reconstructs the same tree.
*
* Approach:
* Pre-order DFS. serialize emits each node's value (or "#" for null) so the
* structure is fully captured. deserialize consumes the tokens in the same
* pre-order, recursively building left then right; a "#" yields a null child.
*
* Time: O(n) for both directions.
* Space: O(n)
*/
export function serialize(root: TreeNode | null): string {
const tokens: string[] = [];
function dfs(node: TreeNode | null): void {
if (!node) {
tokens.push("#");
return;
}
tokens.push(String(node.val));
dfs(node.left);
dfs(node.right);
}
dfs(root);
return tokens.join(",");
}
export function deserialize(data: string): TreeNode | null {
const tokens = data.split(",");
let i = 0;
function build(): TreeNode | null {
const token = tokens[i++];
if (token === "#") return null;
const node = new TreeNode(Number(token));
node.left = build();
node.right = build();
return node;
}
return build();
}