剑指 Offer 37. 序列化二叉树
思路:层序遍历
serialize
- 初始化:队列queue,结果res
- 从队列中取出节点:
- 若节点为空,打印字符串"null,"
- 若节点不为空,打印对应数字,将左右子节点加入queue
- 返回值:res
deserialize
- 初始化:队列queue,根节点root
- 从队列取出当前节点cur
- 遍历字符串,若当前值不为空,构造cur->left,并加入队列
- 遍历字符串,若当前值不为空,构造cur->right,并加入队列
- 返回根节点
/**
* 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) {
queue<TreeNode*> q;
q.push(root);
string ans;
while(q.size()){
TreeNode* cur=q.front();
q.pop();
if(cur==nullptr){
ans+="null,";
}
else{
ans+=to_string(cur->val)+",";
q.push(cur->left);
q.push(cur->right);
}
}
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int i=0,j=0;
while(j<data.size()&&data[j]!=',')++j;
string s=data.substr(i,j-i);
if(s=="null") return nullptr;
TreeNode* root=new TreeNode(stoi(s));
queue<TreeNode*> q;
q.push(root);
while(q.size()){
TreeNode* cur=q.front();
q.pop();
i=j+1;
j++;
while(j<data.size()&&data[j]!=',')++j;
string s=data.substr(i,j-i);
if(s!="null"){
cur->left=new TreeNode(stoi(s));
q.push(cur->left);
}
i=j+1;
j++;
while(j<data.size()&&data[j]!=',')++j;
s=data.substr(i,j-i);
if(s!="null"){
cur->right=new TreeNode(stoi(s));
q.push(cur->right);
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
时间复杂度 O(n)
空间复杂度 O(n)