-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
71 lines (66 loc) · 1.84 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Definition for _Node.
* class _Node {
* val: number
* children: _Node[]
*
* constructor(v: number) {
* this.val = v;
* this.children = [];
* }
* }
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
class Codec {
constructor() {}
// Encodes an n-ary tree to a binary tree.
serialize(root: _Node | null): TreeNode | null {
if (root === null) {
return null;
}
const node = new TreeNode(root.val);
if (root.children.length === 0) {
return node;
}
let left: TreeNode | null = this.serialize(root.children[0]);
node.left = left;
for (let i = 1; i < root.children.length; i++) {
if (left) {
left.right = this.serialize(root.children[i]);
left = left.right;
}
}
return node;
}
// Decodes your binary tree back to an n-ary tree.
deserialize(root: TreeNode | null): _Node | null {
if (root === null) {
return null;
}
const node = new _Node(root.val);
if (root.left === null) {
return node;
}
let left: TreeNode | null = root.left;
while (left !== null) {
node.children.push(this.deserialize(left));
left = left.right;
}
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));