File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
serialize-and-deserialize-binary-tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments