Skip to content

Commit 221da7b

Browse files
committed
Feat: 297. Serialize and Deserialize Binary Tree
1 parent c1b5919 commit 221da7b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
/**
13+
* https://leetcode.com/problems/serialize-and-deserialize-binary-tree
14+
* T.C. O(n)
15+
* S.C. O(n)
16+
*/
17+
function serialize(root: TreeNode | null): string {
18+
return JSON.stringify(root);
19+
}
20+
21+
function deserialize(data: string): TreeNode | null {
22+
return JSON.parse(data);
23+
}
24+
25+
/**
26+
* Recursive
27+
* T.C. O(n)
28+
* S.C. O(n)
29+
*/
30+
function serialize(root: TreeNode | null): string {
31+
return root
32+
? `${root.val},${serialize(root.left)},${serialize(root.right)}`
33+
: 'null';
34+
}
35+
36+
function deserialize(data: string): TreeNode | null {
37+
const values = data.split(',');
38+
let index = 0;
39+
40+
function dfs(): TreeNode | null {
41+
const val = values[index++];
42+
if (val === 'null') return null;
43+
44+
const node = new TreeNode(parseInt(val));
45+
node.left = dfs();
46+
node.right = dfs();
47+
return node;
48+
}
49+
50+
return dfs();
51+
}

0 commit comments

Comments
 (0)