题目:
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 tree. There
is no restriction on how your serialization/deserialization algorithm
should work. You just need to ensure that a binary tree can be
serialized to a string and this string can be deserialized to the
original tree structure.
大意就是将一个二叉树序列化为一个string和将string反序列化之后,使之和原二叉树一样。
这里关键是如何去根据二叉树构造string,也就是按什么样的遍历方法来构造string。
直观上容易接受的是按照层序遍历来构造,好处是序列化的时候很容易,使用一个队列即可实现,但难的是反序列化的时候,不好将二叉树重新构造出来。
后来决定根据dfs的顺序,也就是先序遍历来构造string,利用递归的特性,序列化和反序列化都是比较容易的。
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
stringstream ss;
serializeDFS(root, ss);
ss >> res;
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int cnt = 0;
return deserializeDFS(data, cnt);
}
private:
void serializeDFS(TreeNode* root, stringstream &ss) {
if(!root) {ss << "N,"; return;}
ss << root->val;
ss << ",";
serializeDFS(root->left, ss);
serializeDFS(root->right, ss);
}
TreeNode* deserializeDFS(const string& data, int& cnt) {
if(cnt >= data.size()) return nullptr;
if(data[cnt] == 'N') {
cnt += 2;
return nullptr;
}
int num = getNum(data, cnt);
auto root = new TreeNode(num);
root->left = deserializeDFS(data, cnt);
root->right = deserializeDFS(data, cnt);
return root;
}
int getNum(const string& data, int& cnt) {
int res = 0;
bool negFlag = false;
if(data[cnt] == '-') {
negFlag = true;
++cnt;
}
while(data[cnt] != ',') {
res = res*10 + (data[cnt]-'0');
++cnt;
}
++cnt;
if(negFlag) res *= (-1);
return res;
}
};