AC代码。 c++版本的。
序列化Binary Tree。 这里因为给定的Tree的val是Integer,所以我们可以用一个字符型的常量当做delimiter,比如','。然后我们可以使用两种方法, pre-order traversal,或者level-order traversal。两种方法的时间复杂度和空间复杂度都一样。下面是pre-order traversal的:
Time Complexity - O(n), Space Compleixty - O(n)
/**
* 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 recursive(TreeNode* root,int father,int & cur,string & re,int type){
if(!root) return ;
if(cur>0) re+=",";
re+=(to_string(father)+"-"+to_string(cur));
if(type==1){
re+="_l";
}else{
re+="_r";
}
re+=":";
re+=(to_string(root->val));
father = cur;
cur++;
recursive(root->left,father,cur,re,1);
recursive(root->right,father,cur,re,2);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root) return "";
string re="";
int cur=0;
recursive(root,0,cur,re,1);
return re;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return NULL;
unordered_map<int,TreeNode*> hash;
size_t begin=0;
size_t end;
do{
end = data.find(',',begin);
string item=data.substr(begin,end-begin);
// item = key1-key2_type:vlaue
size_t t1=item.find('-');
size_t t2=item.find('_');
size_t t3=item.find(':');
TreeNode* node = new TreeNode(stoi(item.substr(t3+1,item.size()-t3-1)));
int key1 = stoi(item.substr(0,t1));
int key2 = stoi(item.substr(t1+1,t2-t1-1));
string type = item.substr(t2+1,t3-t2-1);
hash[key2]=node;
if(key2>0){
if(type =="l"){
hash[key1]->left=node;
}else{
hash[key1]->right=node;
}
}
begin = end+1;
}while(end != string::npos);
return hash[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
上述方法记录了所有关系。还有更简化的方法。
需要记录每个节点前有多少个 null 节点,就可以找出该节点的孩子在哪里了,其左右孩子分别为 2*(i-num)+1 和 2*(i-num)+2(num为当前节点之前 null 节点的个数)。