Serialize and Deserialize Binary Tree(C++二叉树的序列化与反序列化)
(1)先序遍历+队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root) return "nullptr,";
return to_string(root->val)+','+serialize(root->left)+serialize(root->right);
}
TreeNode *helper(queue<string> &q) {
string s=q.front();
q.pop();
if(s=="nullptr") return nullptr;
TreeNode *root=new TreeNode(stoi(s));
root->left=helper(q);
root->right=helper(q);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
queue<string> q;
string s="";
for(int i=0;i<data.length();i++) {
if(data[i]==',') {
q.push(s);
s="";
} else s+=data[i];
}
return helper(q);
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
还没有评论,来说两句吧...