Article Directory
Method 1: dfs: time O(n), space O(n)
answer:
- Serialization:
- Specifies the format of serialization: a data followed by a comma, if the tree is empty, use # to replace the placeholder
- First traverse the binary tree, if it is an empty tree, insert #, if it is not empty, convert the data to string type and insert it, and add a comma at the end
- Deserialization
- Deserialize according to the serialized format, if the current character is #, then empty
- If it is not #, create a node dynamically
Time: O(n) to traverse all nodes of the binary tree, all elements of the traversal string are O(n)
space: O(n) The worst-case binary tree is a single tree, requiring O(n) recursion space
/**
* 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 ans;
void dfs(TreeNode* root)
{
if (root == nullptr)
{
ans.push_back('#');
return;
}
ans.append(to_string(root->val));
ans.push_back(',');
dfs(root->left);
dfs(root->right);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root)
{
dfs(root);
return ans;
}
int index = 0;
TreeNode* Decodes(string& data)
{
TreeNode* root = nullptr;
if (data[index] == '#')
{
index++;
return root;
}
int pos = index;
while (data[pos] != ',')
pos++;
int val = stoi(data.substr(index, pos - index));
root = new TreeNode(val);
index = pos + 1;
root->left = Decodes(data);
root->right = Decodes(data);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data)
{
TreeNode* root = Decodes(data);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));