Leetcode 297. 二叉树的序列化与反序列化
题目
序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
题解
对于序列化,我才用的是先序遍历,每个节点的值之间用 . 分割,无子节点用n表示。
反序列化,利用栈完成,
获取栈顶的节点,如果其左子树为NULL且当前节点值不是n,则说明有左子树。我们就获取数值,创建左子树,同时压入栈中。其他情况下,若当前节点值为n,则说明无左子树;若左子树不是NULL,则说明左子树以构建完成,开始构建右子树。详细过程见代码
代码
/**
* 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) { //中序遍历进行序列化,节点间用 . 分割;无子树用n表示
if(root == NULL) return "n.";
string ans = to_string(root->val) + ".";
ans += serialize(root->left);
ans += serialize(root->right);
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int n=data.length();
int i=0;
if(data[i] == 'n') return nullptr;
stack<TreeNode*> sp;
bool isF = false;
int now=0;
if(data[i] == '-'){
isF = true;
i++;
}
while(data[i]!='.'){
now = now*10 + (data[i]-'0');
i++;
}
if(isF) now = -now;
TreeNode* root = new TreeNode(now);
sp.push(root);
while(!sp.empty()){
if(data[i] == '.') i++;
TreeNode* t = sp.top();
if(data[i] =='n' || t->left!=NULL){ //前者表示无左子树;后者表明左子树已构建完毕
if(t->left==NULL){
t->left = nullptr;
i+=2;
}
if(data[i] == 'n'){
t->right = nullptr;
sp.pop();
}else{
isF = false;
now = 0;
if(data[i] == '-'){
isF = true;
i++;
}
while(data[i]!='.'){
now = now*10 + (data[i]-'0');
i++;
}
if(isF) now = -now;
TreeNode* newT = new TreeNode(now);
t->right = newT;
sp.pop();
sp.push(newT);
}
}else{
isF = false;
now = 0;
if(data[i] == '-'){
isF = true;
i++;
}
while(data[i]!='.'){
now = now*10 + (data[i]-'0');
i++;
}
if(isF) now = -now;
TreeNode* newT = new TreeNode(now);
t->left = newT;
sp.push(newT);
}
i += 1;
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。