AcWing 50. 序列化二叉树
原题链接
困难
作者:
adamXu
,
2020-10-06 14:19:28
,
所有人可见
,
阅读 340
/**
* 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) {
//序列化与反序列化
//如果为空节点,往res 中加null即可,如果非空,加上本身的值,对左右子树进行递归
//反序列化,如果为null则直接返回空节点,处理下一个即可,如果u == size 说明处理完毕
//返回即可,如果非空则对左右继续处理
string res;
dfs_s(root,res);
//cout << res << endl;
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++;
if(data[u] == 'n'){
u = k + 1;
return nullptr;
}
int val = 0;
if(data[u] == '-'){
for(int i = u + 1;i < k;++i) val = 10 * val + data[i] - '0';
val *= -1;
}
else{
for(int i = u;i < k;++i) val = 10 * val + data[i] - '0';
}
u = k + 1;
TreeNode* root = new TreeNode(val);
root->left = dfs_d(data,u);
root->right = dfs_d(data,u);
return root;
}
};