剑指offer-61:序列化二叉树
选择基于前序遍历来实现二叉树的序列化;如果当前节点为空,保存NULL或者自己设置的转换编码,如果当前节点非空,则保留一个数字和空格;反序列化过程类似,如果传递到字符串的尾端,便退出,通过变量k记录每个二叉树节点数值的位数,如果当前字符串为序列化设置的NULL,便可以回到下一个节点数值的首位,并将每个字符串转换为对应二叉树节点的数值。同时需要注意负数的情况,由于整个二叉树所有节点只遍历一次,因此时间复杂度为O(n)。
具体代码如下:
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
dfs1(root, res);
return res;
}
void dfs1(TreeNode* root, string &res){
if(!root){
res +="NULL";
return;
}
res += to_string(root->val) + ' ';
dfs1(root->left, res);
dfs1(root->right, res);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int u = 0;
dfs2(data, u);
}
TreeNode* dfs2(string &data, int &u){
if(data[u]=='N'){
u += 4;
return NULL;
}
int t = 0;
bool is_minus = false;
while(data[u] != ' '){
if(data[u] == '-') is_minus = true;
else t = t * 10 + data[u] - '0';
u++; // 在123, 12这些数的数位中向右移动
}
u++; // 回到下一个数字的首部,因为123和12这些数之间隔了一位' '
if(is_minus) t = -t;
auto root = new TreeNode(t);
root->left = dfs2(data, u);
root->right = dfs2(data, u);
return root;
}
};