AcWing 50. 序列化二叉树
原题链接
困难
作者:
minux
,
2020-04-23 15:26:28
,
所有人可见
,
阅读 409
/**
* 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) {
string res;
dfsEn(root, res);
return res;
}
void dfsEn(TreeNode* node, string &res){
if(!node){
res+="#,";
return;
}
res+=to_string(node->val)+",";
dfsEn(node->left, res);
dfsEn(node->right, res);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int pos=0;
return dfsDe(data, pos);
}
TreeNode* dfsDe(string data, int& pos){
if(data[pos]=='#'){
pos+=2;
return nullptr;
}
bool neg=false;
if(data[pos]=='-'){neg=true; pos++;}
int v=0;
while(data[pos]!=','){
v=v*10+data[pos]-'0';
pos++;
}
pos++;
if(neg) v=-v;
TreeNode *node = new TreeNode(v);
node->left = dfsDe(data, pos);
node->right = dfsDe(data, pos);
return node;
}
};