您的位置:首页 > 编程语言 > C语言/C++

二叉树的序列化和反序列化

2015-09-01 20:56 393 查看
        该题首先用先序遍历的思路把树转换(序列化)为字符串,这样在恢复的时候就可以根据字符串先序遍历的特点进行恢复(反序列化)。

string int2str(int intsrc){
stringstream ss;
ss << intsrc;
return ss.str();
}
//序列化代码,先序遍历的顺序进行序列化
string serialize(TreeNode *root) {
// write your code here
string sec;
if(root == nullptr){
sec += "# ";
}else{
sec += int2str(root -> val);
sec += " ";
sec += serialize(root -> left);
sec += serialize(root -> right);
}
return sec;
}

/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
//找到序列中下一个树的节点字符串
int pos = 0;
string nextString(string src){
string result;
if(pos < src.length()){
if(src[pos] == ' '){
pos++;
}
while(src[pos] != ' '){
result += src[pos];
pos++;
}
return result;
}
}

int str2int(string strsrc){
return atoi(strsrc.c_str());
}
//反序列化,根据字串先序遍历的特点
TreeNode *deserialize(string data) {
// write your code here
string cur = nextString(data);
if(cur == "#"){
return nullptr;
}else{
TreeNode *root = new TreeNode(str2int(cur));
root -> left = deserialize(data);
root -> right = deserialize(data);
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 二叉树 代码