LeetCode 297. Serialize and Deserialize Binary Tree
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.
Example:
You may serialize the following tree:
1
/ \
2 3
/ \
4 5
as "[1,2,3,null,null,4,5]"
Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
解析:对二叉树进行序列化和反序列化。
序列化的过程类似于二叉树的层次遍历的过程,考虑BFS借助队列进行。先将树的跟节点入队列,然后打印数值,然后再把根节点的左子树和右子树分别;进队列,然后循环出队列遍历。可以得到序列化的部分代码如下:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
queue<TreeNode*> que;
if(root)
que.push(root);
while(!que.empty())
{
TreeNode* t = que.front();
que.pop();
if(t)
{
out << t->val <<' ';
que.push(t->left);
que.push(t->right);
}else
{
out <<"# ";
}
}
return out.str();
}
对于反序列化,也是采用队列,进行DFS处理。先取出第一个字符,生成根节点,然后把根节点入队列。然后分别取出后面的字符,分别生成二叉树节点,作为根节点的左子树和右子树。
反序列化的代码如下:
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty())
return NULL;
istringstream in(data);
queue<TreeNode*> que;
string val;
in >> val;
TreeNode *root = new TreeNode(stoi(val)), *cur = root;
que.push(cur);
while(!que.empty())
{
TreeNode *t = que.front();
que.pop();
if(!(in >> val))
break;
if(val != "#")
{
cur = new TreeNode(stoi(val));
que.push(cur);
t->left = cur;
}
if(!(in >> val))
break;
if(val != "#")
{
cur = new TreeNode(stoi(val));
que.push(cur);
t->right = cur;
}
}
return root;
}