题目地址:https://leetcode.com/problems/serialize-and-deserialize-binary-tree/#/description
题目描述: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.
我的代码:
/**
* 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:
void add_tree_to_str(TreeNode* root,string& str){
if(root==NULL){
str+="null,";
return;
}
str+=(to_string(root->val)+",");
add_tree_to_str(root->left,str);
add_tree_to_str(root->right,str);
}
void add_str_to_tree(TreeNode* tree,string &data,int& start){
int now=start;
for(;start<data.size();start++)
if(data[start]==',')break;
if(data.substr(now,start-now)!="null"){
tree->left=new TreeNode(atoi(data.substr(now,start-now).c_str()));
start++;
add_str_to_tree(tree->left,data,start);
}
start++;
now=start;
for(;start<data.size();start++)
if(data[start]==',')break;
if(data.substr(now,start-now)!="null"){
tree->right=new TreeNode(atoi(data.substr(now,start-now).c_str()));
start++;
add_str_to_tree(tree->right,data,start);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string str="";
if(!root) return str;
add_tree_to_str(root,str);
return str;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* tree;
if(data=="") return tree;
int start=0;
for(;start<data.size();start++)
if(data[start]==',')
break;
string s=data.substr(0,start);
tree=new TreeNode(atoi(s.c_str()));
start++;
add_str_to_tree(tree,data,start);
return tree;
}
};
解题思路:
我的答案采用前序遍历来转换树与字符串,为方便区分左子树与右子树,我将所有的空节点(包括叶节点的两个空子节点)表示为null存储在字符串中,于是通过递归调用很容易将树转换成字符串。前序遍历的复杂度为O(n)。
然后是将前序遍历后生产的字符串转换为树。仍然采用递归调用。对任意非空树,先保存其根节点,然后对根节点递归获取其左子树,然后再获取其又子树。由于所有的空节点,包括叶节点的两个空节点都用“null”表示在字符串中。所以递归到其叶节点后,递归过程会自然的结束。由于该过程对字符串只需顺序遍历一次,所以复杂度为O(n)。