题目链接

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));

本文介绍了一种使用深度优先搜索(DFS)算法来实现二叉树的序列化与反序列化的方法。通过DFS遍历,将二叉树转化为字符串,再将字符串还原为二叉树结构。该方法适用于需要在网络上传输或存储二叉树结构的场景。
2796

被折叠的 条评论
为什么被折叠?



