-
Notifications
You must be signed in to change notification settings - Fork 112
/
0428-SerializeAndDeserializeNAryTree.cs
109 lines (93 loc) · 3.03 KB
/
0428-SerializeAndDeserializeNAryTree.cs
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//-----------------------------------------------------------------------------
// Runtime: 408ms
// Memory Usage: 51.9 MB
// Link: https://leetcode.com/submissions/detail/378975764/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
/*
// Definition for a Node.
public class Node {
public int val;
public IList<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, IList<Node> _children) {
val = _val;
children = _children;
}
}
*/
public class _0428_SerializeAndDeserializeNAryTree
{
private readonly string SPLITTER = ",";
private readonly string NULL = "null";
// Encodes a tree to a single string.
public string serialize(Node root)
{
if (root == null) return NULL;
var dummy = new Node(-1, new List<Node>());
dummy.children.Add(root);
var queue = new Queue<Node>();
queue.Enqueue(dummy);
var sb = new StringBuilder();
while (queue.Count > 0)
{
var size = queue.Count;
for (int i = 0; i < size; i++)
{
var node = queue.Dequeue();
foreach (var child in node.children)
{
sb.Append(child.val);
sb.Append(SPLITTER);
queue.Enqueue(child);
}
sb.Append(NULL);
sb.Append(SPLITTER);
}
}
return sb.ToString();
}
// Decodes your encoded data to tree.
public Node deserialize(string data)
{
var split = data.Split(new string[] { SPLITTER }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1 && split[0] == NULL) return null;
var dummy = new Node(-1, new List<Node>());
var queue = new Queue<Node>();
queue.Enqueue(dummy);
foreach (var value in split)
{
if (value == NULL)
{
queue.Dequeue();
continue;
}
var node = new Node(int.Parse(value), new List<Node>());
queue.Peek().children.Add(node);
queue.Enqueue(node);
}
return dummy.children[0];
}
public class Node
{
public int val;
public IList<Node> children;
public Node() { }
public Node(int _val, IList<Node> _children)
{
val = _val;
children = _children;
}
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
}