Skip to content

Commit d60724c

Browse files
committed
add Serialize and Deserialize Binary Tree solution
1 parent 8a26cf0 commit d60724c

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+
* [Problem]: [297] Serialize and Deserialize Binary Tree
3+
* (\https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/)
4+
*/
5+
6+
class TreeNode {
7+
val: number;
8+
left: TreeNode | null;
9+
right: TreeNode | null;
10+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
11+
this.val = val === undefined ? 0 : val;
12+
this.left = left === undefined ? null : left;
13+
this.right = right === undefined ? null : right;
14+
}
15+
}
16+
17+
/*
18+
* Encodes a tree to a single string.
19+
*/
20+
//시간복잡도 O(N)
21+
//공간복잡도 O(N)
22+
function serialize(root: TreeNode | null): string {
23+
if (!root) return "NULL";
24+
25+
const left = serialize(root.left);
26+
const right = serialize(root.right);
27+
28+
return `${root.val},${left},${right}`;
29+
}
30+
31+
/*
32+
* Decodes your encoded data to tree.
33+
*/
34+
//시간복잡도 O(N)
35+
//공간복잡도 O(N)
36+
function deserialize(data: string): TreeNode | null {
37+
const values = data.split(",");
38+
let index = 0;
39+
40+
function dfs(): TreeNode | null {
41+
if (values[index] === "NULL") {
42+
index++;
43+
return null;
44+
}
45+
const node = new TreeNode(+values[index++]);
46+
47+
node.left = dfs();
48+
node.right = dfs();
49+
50+
return node;
51+
}
52+
53+
return dfs();
54+
}

0 commit comments

Comments
 (0)