题目描述
题解:
/**
* 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 "[null]";
queue<TreeNode*> q;
q.push(root);
string ret = "[";
while(!q.empty()){
TreeNode *tmp = q.front();
q.pop();
if(tmp){
q.push(tmp->left);
q.push(tmp->right);
ret += to_string(tmp->val) + ",";
}else{
ret += "null,";
}
}
ret[ret.length()-1] = ']';
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data == "[null]") return nullptr;
vector<string> datas;
int l = 1 , r = 2 ;
while(r < data.length()){
if(data[r] == ',' || data[r] == ']'){
datas.push_back(data.substr(l,r-l));
l = r + 1;
r = l ;
}
++r;
}
TreeNode *root = new TreeNode(stoi(datas[0]));
queue<TreeNode*> q;
q.push(root);
// q.push(root);
int index = 1;
while(!q.empty()){
TreeNode *node = q.front();
q.pop();
if(node !=nullptr){
node->left = datas[index] == "null" ? nullptr : new TreeNode(stoi(datas[index]));
++index;
node->right = datas[index] == "null" ? nullptr : new TreeNode(stoi(datas[index]));
++index;
q.push(node->left);
q.push(node->right);
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));