lurenaa的博客

递归实现

  先序遍历,类似于数组表示二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Codec {
public:
void se_helper(TreeNode* root, string& str) {
if(!root) {
str += "x#";
return ;
}
str += to_string(root->val) + '#';
se_helper(root->left, str);
se_helper(root->right, str);
}

// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s;
se_helper(root, s);
// cout <<s << endl;
return s;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data == "x#")
return nullptr;
auto iter = data.begin();
return deserialize1(iter, data.end());
}

TreeNode* deserialize1(string::iterator& iter, string::iterator end)
{
if(iter == end)
return nullptr;
string s;
while(*iter != '#') {
s += *iter++;
}
++iter;
if(s == "x")
return nullptr;
int val = atoi(s.c_str());
TreeNode* newOne = new TreeNode(val);
newOne->left = deserialize1(iter, end);
newOne->right = deserialize1(iter, end);
return newOne;
}
};

Accepted

62/62 cases passed (32 ms)

Your runtime beats 87.21 % of cpp submissions

Your memory usage beats 43.82 % of cpp submissions (24.2 MB)