question:
The source of the problem is this question from LeetCode:LCR 048. Serialization and deserialization of binary trees - LeetCode
I thought it was okay, just do preorder traversal. The time and space complexity are both O(n), so I should be able to get rid of the problem K.
Question code:
/**
* 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:
list<string> str2lst(string str)
{
list<string> ret;
string cur = "";
for(int i =0;i<str.size();++i){
if(str[i] ==' '){
if(cur.size()>0){
ret.push_back(cur);
cur ="";
}
continue;
}
cur = cur + str[i];
}
return ret;
}
TreeNode * dfs2(list<string> & arr) //反序列化
{
if(arr.front()=="*"){
arr.erase(arr.begin());
return nullptr;
}
TreeNode * cur = new TreeNode(stoi(arr.front()));
arr.erase(arr.begin());
cur->left = dfs2(arr);
cur->right = dfs2(arr);
return cur;
}
void dfs(TreeNode * root,string & s){
if(root == nullptr){
s.push_back('*');
s =s + " ";
return;
}
s=s+(to_string(root->val)+" ");
dfs(root->left,s);
dfs(root->right,s);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string ret = "";
dfs(root,ret);
return ret;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size()==0){
return nullptr;
}
list<string> arr = str2lst(data);
return dfs2(arr);
}
};
result:
Stuck example:
(However, the amount of data does not exceed the scope of the question)
And I compared it with the official solution, and the ideas are almost exactly the same.
But my code times out. . . .
analyze:
So how could I let go of such a weird event? Then I modified my code bit by bit to run the test to see where the problem was.
Finally found the code of the problem:
s=s+(to_string(root->val)+" ");
change it to
s+=(to_string(root->val)+" ");
The code will pass. . . . . .
Because if you use the former, a new temporary string object will be created during the execution process, which will double the memory usage and consume a lot of time (especially when s here is actually very large, the additional time and space costs will be higher).
so,
The "higher" here may actually make a huge difference.
In the usual development process, you should develop the habit of using more efficient syntax.