-
Notifications
You must be signed in to change notification settings - Fork 481
/
0297.cpp
42 lines (38 loc) · 860 Bytes
/
0297.cpp
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
class Codec
{
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root)
{
preOrder(root);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data)
{
stringstream in(data);
return deOrder(in);
}
private:
string res;
void preOrder(TreeNode* root)
{
if (root == nullptr)
{
res += "# "; return ;
}
res += to_string(root->val) + ' ';
preOrder(root->left);
preOrder(root->right);
}
TreeNode* deOrder(stringstream& in)
{
string val;
in >> val;
if (val == "#") return nullptr;
TreeNode* root = new TreeNode(stoi(val));
root->left = deOrder(in);
root->right = deOrder(in);
return root;
}
};