forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
49 lines (43 loc) · 1.41 KB
/
Solution.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Codec {
public string serialize(TreeNode root) {
return rserialize(root, "");
}
public TreeNode deserialize(string data) {
string[] dataArray = data.Split(",");
LinkedList<string> dataList = new LinkedList<string>(dataArray.ToList());
return rdeserialize(dataList);
}
public string rserialize(TreeNode root, string str) {
if (root == null) {
str += "None,";
} else {
str += root.val.ToString() + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}
public TreeNode rdeserialize(LinkedList<string> dataList) {
if (dataList.First.Value.Equals("None")) {
dataList.RemoveFirst();
return null;
}
TreeNode root = new TreeNode(int.Parse(dataList.First.Value));
dataList.RemoveFirst();
root.left = rdeserialize(dataList);
root.right = rdeserialize(dataList);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));