Leetcode Answers 449

今晚最后一题,又是一道serialize/deserialize的题,依然是熟悉的queue来解决。

题目:
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.

思路:
又见到了熟悉的Serialization,而且还是在BST这种基本上是balanced树上,简直是送分题。依然还是用Queue来进行level order traversal,用List来存值,最后join得到serialized string,然后反着用Queue,甚至不需要用到BST自己的特点(val: left < root < right),单纯用index一次看两个就可以了。如果不放心就检查val,小的在左边大的在右边。最后返回root得到deserialized tree。

Answer:

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
/**
* 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 {
// Encodes a tree to a single string.
public string serialize(TreeNode root) {
if(root == null) return null;
var que = new Queue<TreeNode>();
var ret = new List<string>();
que.Enqueue(root);
while(que.Count > 0){
var n = que.Dequeue();
if(n != null){
ret.Add(n.val.ToString());
que.Enqueue(n.left);
que.Enqueue(n.right);
}else{
ret.Add("#");
}
}
return string.Join(",", ret);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(string data) {
if(data == null) return null;
var list = data.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
if(list.Length == 0) return null;
var root = new TreeNode(int.Parse(list[0]));
var que = new Queue<TreeNode>();
que.Enqueue(root);
for(int i = 1;i<list.Length;i+=2){
var n = que.Dequeue();
if(!list[i].Equals("#")){
n.left = new TreeNode(int.Parse(list[i]));
que.Enqueue(n.left);
}
if(i+1<list.Length && !list[i+1].Equals("#")){
n.right = new TreeNode(int.Parse(list[i+1]));
que.Enqueue(n.right);
}
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

考察:基本上二叉树都可以这么做,哪怕死记硬背下来也是好的。

以上。

17-04-27
@Sturbridge