1
+ /**
2
+ * Definition for node.
3
+ * class Node {
4
+ * val: number
5
+ * children: Node[]
6
+ * constructor(val?: number) {
7
+ * this.val = (val===undefined ? 0 : val)
8
+ * this.children = []
9
+ * }
10
+ * }
11
+ */
12
+
13
+ /**
14
+ * Problem: Leet Code 428
15
+ * Solution: Uses the depth 1st traversal to serialize and deserialize the N-Ary tree. The ser and deser process
16
+ * uses a special marker with null(empty string) to determine that the current branch has ended. This helps us
17
+ * determine, that we have to backtrack and start adding new elements to the parents childs and so on.
18
+ *
19
+ * Time: O(n) since all the nodes needs to be traversed at least once. Spsace: O(n) since at least additional space
20
+ * of n items is required.
21
+ *
22
+ */
23
+ class Codec {
24
+ constructor ( ) {
25
+
26
+ }
27
+
28
+ // Encodes a tree to a single string.
29
+ serialize ( root : Node | null ) : string {
30
+ const serialized : string [ ] = [ ]
31
+ this . serializeHelper ( root , serialized ) ;
32
+
33
+ return serialized . join ( ";" ) ;
34
+ } ;
35
+
36
+ serializeHelper ( root : Node | null , serialized : string [ ] ) {
37
+ if ( root === null ) return
38
+ serialized . push ( root . val . toString ( ) )
39
+ if ( root . children . length === 0 ) {
40
+ // Found a leaf node, ending a terminating null;
41
+ serialized . push ( "" )
42
+ } else {
43
+ root . children . forEach ( child => this . serializeHelper ( child , serialized ) ) ;
44
+ serialized . push ( "" )
45
+ }
46
+ }
47
+
48
+ // Decodes your encoded data to tree.
49
+ deserialize ( data : string ) : Node | null {
50
+ const elements = data . split ( ";" )
51
+ return this . deserializeHelper ( elements ) ;
52
+ } ;
53
+
54
+ deserializeHelper ( elements : string [ ] ) : Node | null {
55
+ const value = elements . shift ( ) ;
56
+ if ( value === undefined || value === "" ) return null ;
57
+ const root = new Node ( parseInt ( value ) ) ;
58
+ let child ;
59
+ while ( ( child = this . deserializeHelper ( elements ) ) !== null ) {
60
+ root . children . push ( child )
61
+ }
62
+ return root ;
63
+ }
64
+ }
65
+
66
+ // Your Codec object will be instantiated and called as such:
67
+ // Codec codec = new Codec();
68
+ // codec.deserialize(codec.serialize(root));
0 commit comments