Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ publicclassCodec {
// Encodes a tree to a single string. publicstringserialize(TreeNode root) { }
// Decodes your encoded data to tree. public TreeNode deserialize(string data) { } }
// Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
#解題
serialize
案例一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[TestMethod()] publicvoidserializeTest() { //arrange var node = new TreeNode(1); var sut = new Codec();
[TestMethod()] publicvoiddeserializeTest() { //arrange var nodeSerializeString = @"1!#!#!"; var sut = new Codec(); var expected = new TreeNode(1); //act var actual = sut.deserialize(nodeSerializeString);
string res = root.val + "!"; res += serialize(root.left); res += serialize(root.right); return res; }
// Decodes your encoded data to tree. public TreeNode deserialize(string data) { var nodeData = data.Split(newstring[] { "!" }, StringSplitOptions.RemoveEmptyEntries);
var queue = new Queue<string>();
foreach (var node in nodeData) { queue.Enqueue(node); }
return RebuildNode(queue); }
private TreeNode RebuildNode(Queue<string> queue) { var Value = queue.Dequeue();