-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0297_Codec.cc
140 lines (133 loc) · 2.86 KB
/
Problem_0297_Codec.cc
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include "UnitTest.h"
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
public:
// Encodes a tree to a single string.
string serialize(TreeNode *root)
{
deque<string> ans;
if (root == nullptr)
{
ans.push_back("null");
}
else
{
ans.push_back(std::to_string(root->val));
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
root = q.front();
q.pop();
if (root->left != nullptr)
{
ans.push_back(std::to_string(root->left->val));
q.push(root->left);
}
else
{
ans.push_back("null");
}
if (root->right != nullptr)
{
ans.push_back(std::to_string(root->right->val));
q.push(root->right);
}
else
{
ans.push_back("null");
}
}
}
while (!ans.empty() && ans.back() == "null")
{
ans.pop_back();
}
string res;
res.append("[");
string str;
if (!ans.empty())
{
str = ans.front();
ans.pop_front();
}
res.append(str);
while (!ans.empty())
{
str = ans.front();
ans.pop_front();
res.append("," + str);
}
res.append("]");
return res;
}
vector<string> split(string str, string pattern)
{
string::size_type pos;
vector<string> result;
str += pattern; //扩展字符串以方便操作
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data)
{
vector<string> strs = split(data.substr(1, data.length() - 2), ",");
int index = 0;
TreeNode *root = generateNode(strs[index++]);
queue<TreeNode *> q;
if (root != nullptr)
{
q.push(root);
}
while (!q.empty())
{
TreeNode *node = q.front();
q.pop();
node->left = generateNode(index == strs.size() ? "null" : strs[index++]);
node->right = generateNode(index == strs.size() ? "null" : strs[index++]);
if (node->left != nullptr)
{
q.push(node->left);
}
if (node->right != nullptr)
{
q.push(node->right);
}
}
return root;
}
TreeNode *generateNode(string val)
{
if (val.length() == 0 || val == "null")
{
return nullptr;
}
return new TreeNode(stoi(val));
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));