AcWing 50. 序列化二叉树
原题链接
困难
作者:
adamXu
,
2020-09-28 09:23:57
,
所有人可见
,
阅读 366
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
//silu,利用先序遍历,先遍历根节点,加到res中,在递归遍历左右子树
string res;
dfs_s(root,res);
return res;
}
void dfs_s(TreeNode* root,string &res){
if(!root){
res += "null ";
return;
}
res += to_string(root->val) + " ";
dfs_s(root->left,res);
dfs_s(root->right,res);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int u = 0;
return dfs_d(data,u);
}
TreeNode* dfs_d(string data,int &u){
if(u == data.size()) return nullptr;
int k = u;
while(data[k] != ' ') k++; //k用于记录每个单词尾巴空格的位置
//如果该单词为null,直接到下一个单词开头位置
if(data[u] == 'n'){
u = k + 1;
return nullptr;
}
//不是null则处理数字
int val = 0;
if(data[u] == '-'){
for (int i = u+1; i < k; i++) val = val * 10 + data[i] - '0';
val = -val;
}
else{
//如果是数字是正的
for (int i = u; i < k; i++) val = val * 10 + data[i] - '0';
}
u = k + 1; //处理下一个字符串
auto root = new TreeNode(val);
root->left = dfs_d(data,u);
root->right = dfs_d(data,u);
return root;
}
};