Skip to content

Commit b70bf18

Browse files
Jeehay28Jeehay28
authored andcommitted
Add serialize-and-deserialize-binary-tree solution in TS
1 parent ac07f40 commit b70bf18

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
* Encodes a tree to a single string.
14+
*/
15+
16+
// TC: O(n)
17+
// SC: O(n)
18+
function serialize(root: TreeNode | null): string {
19+
if (!root) return "null";
20+
return `${root.val},${serialize(root.left)},${serialize(root.right)}`;
21+
}
22+
23+
/*
24+
* Decodes your encoded data to tree.
25+
*/
26+
27+
// TC: O(n)
28+
// SC: O(n)
29+
function deserialize(data: string): TreeNode | null {
30+
const values = data.split(",");
31+
let idx = 0;
32+
33+
const dfs = () => {
34+
if (values[idx] === "null") {
35+
idx++;
36+
return null;
37+
}
38+
39+
const node = new TreeNode(parseInt(values[idx]));
40+
idx++;
41+
node.left = dfs();
42+
node.right = dfs();
43+
return node;
44+
};
45+
46+
return dfs();
47+
}
48+
49+
/**
50+
* Your functions will be called as such:
51+
* deserialize(serialize(root));
52+
*/

0 commit comments

Comments
 (0)