LeetCode 297. Serialize and Deserialize Binary Tree

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
class Codec {
public:
string serialize(TreeNode* root) {
string ans;
dfs(root, ans);
return ans;
}
void dfs(TreeNode* root, string& curr) {
if (!root) {
curr += "null,";
return;
}
curr += to_string(root->val) + ",";
dfs(root->left, curr);
dfs(root->right, curr);
}
TreeNode* deserialize(string data) {
istringstream ss(data);
string s;
function<TreeNode*(void)> dfs = [&]() {
TreeNode* ans;
if (getline(ss, s, ',')) {
ans = parse(s);
if (ans) {
ans->left = dfs();
ans->right = dfs();
}
}
return ans;
};
return dfs();
}
TreeNode* parse(string& s) {
if (s == "null") return nullptr;
return new TreeNode(stoi(s));
}
};