-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_STOII_0048_Codec.cc
More file actions
84 lines (76 loc) · 1.55 KB
/
Problem_STOII_0048_Codec.cc
File metadata and controls
84 lines (76 loc) · 1.55 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
public:
void rseralize(TreeNode *root, string &str)
{
if (root == nullptr)
{
str += "Null,";
}
else
{
str += to_string(root->val) + ",";
rseralize(root->left, str);
rseralize(root->right, str);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode *root)
{
string ans;
rseralize(root, ans);
return ans;
}
TreeNode *rdeserialize(list<string> &dataArray)
{
if (dataArray.front() == "Null")
{
dataArray.erase(dataArray.begin());
return nullptr;
}
TreeNode *root = new TreeNode(stoi(dataArray.front()));
dataArray.erase(dataArray.begin());
root->left = rdeserialize(dataArray);
root->right = rdeserialize(dataArray);
return root;
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data)
{
list<string> dataArray;
string str;
for (auto &ch : data)
{
if (ch == ',')
{
dataArray.push_back(str);
str.clear();
}
else
{
str.push_back(ch);
}
}
if (!str.empty())
{
dataArray.push_back(str);
str.clear();
}
return rdeserialize(dataArray);
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));