Skip to content

Commit 426eb1f

Browse files
committed
feat(typescript): add ts solution for leetcode 297
1 parent 3dca353 commit 426eb1f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
15+
/*
16+
* Encodes a tree to a single string.
17+
*/
18+
function serialize(root: TreeNode | null): string {
19+
const box = [];
20+
21+
function cereal(root: TreeNode | null) {
22+
if (root === null) return box.push(null);
23+
box.push(root.val);
24+
cereal(root.left);
25+
cereal(root.right);
26+
}
27+
cereal(root);
28+
29+
return box.join(',');
30+
};
31+
32+
/*
33+
* Decodes your encoded data to tree.
34+
*/
35+
function deserialize(data: string): TreeNode | null {
36+
const box: string[] = data.split(',');
37+
38+
function decereal(): TreeNode | null {
39+
const val = box.shift();
40+
if (val === '') return null;
41+
const node = new TreeNode(Number(val));
42+
node.left = decereal();
43+
node.right = decereal();
44+
return node;
45+
}
46+
47+
return decereal();
48+
};
49+
50+
51+
/**
52+
* Your functions will be called as such:
53+
* deserialize(serialize(root));
54+
*/

0 commit comments

Comments
 (0)