题目链接
DFS实现序列化和反序列化二叉树
/**
* 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:
string path="";
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
dfs_1(root);
return path;
}
void dfs_1(TreeNode* root)
{
if(!root) path += "@,";
else
{
path += to_string(root->val) + ',';
dfs_1(root->left);
dfs_1(root->right);
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int u = 0;
return dfs_2(data,u);
}
TreeNode* dfs_2(string& data,int& u)
{
if(data[u] == '@')
{
u += 2;
return NULL;
}
else
{
int k = u;
while(data[u] != ',') u++;
TreeNode* root = new TreeNode(stoi(data.substr(k,u-k)));
u++;
root->left = dfs_2(data,u);
root->right = dfs_2(data,u);
return root;
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));