题目链接:剑指 Offer II 048. 序列化与反序列化二叉树
方法:先序遍历(dfs)
解题思路
在先序遍历过程中,节点值之间通过空格隔开,好利于后续反序列化过程中获取值。
代码
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root == nullptr){
return "#";
}
return to_string(root->val) + ' ' + serialize(root->left) + ' ' + serialize(root->right);
}
TreeNode* mydeserialize(istringstream &ss ){
string tmp;
ss >> tmp;
if(tmp == "#"){ // 终止此条路
return nullptr;
}
TreeNode* node = new TreeNode(stoi(tmp));
node->left = mydeserialize(ss);
node->right = mydeserialize(ss);
return node;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream ss(data);
return mydeserialize(ss);
}
};
参考:Kai Zhang
标签:return,string,ss,II,二叉树,TreeNode,序列化,root From: https://www.cnblogs.com/lxycoding/p/17451353.html