因为程序的调用方式是
codec.deserialize(codec.serialize(root));
所以序列化的方式不用按照题目中举例的那样,可以自行定义序列化方式。
如题目中定义的二叉树 [1,2,3,null,null,4,5],在本文的程序中实际被序列化为“1 2 3 null null 4 5 null null null null”。用空格隔开可以方便地使用istringstream操作
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* tmp = q.front();
q.pop();
if (tmp) {
out << tmp->val << " ";
q.push(tmp->left);
q.push(tmp->right);
}
else {
out << "null ";
}
}
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream input(data);
string val;
vector<TreeNode*> vec;//把输入数据全部存为树节点
while (input >> val)
{
if (val != "null")
vec.push_back(new TreeNode(stoi(val)));
else
vec.push_back(NULL);
}
int j = 1;
for (int i = 0; j < vec.size(); i++)
{
if (vec[i] == NULL)//此时j指向下一棵有意义树的左子树;故i继续移动即可
continue;
else
{
if(j<vec.size()) vec[i]->left = vec[j++];
if(j<vec.size()) vec[i]->right = vec[j++];
}
}
return vec[0];//第一元素一定是根节点
}
};