leetcode 297. 二叉树的序列化与反序列化
题目:297. 二叉树的序列化与反序列化 - 力扣(LeetCode)
宽度有限搜索的具象化,没啥难度,注意二叉树中空节点的处理即可。
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (root == nullptr) {
return "[]";
}
vector<TreeNode*> arr;
arr.push_back(root);
int i = 0;
while (i < arr.size()) {
TreeNode* t = arr[i];
i++;
if (!t) {
continue;
}
arr.push_back(t->left);
arr.push_back(t->right);
}
while (arr.size() && arr[arr.size() - 1] == nullptr) {
arr.pop_back();
}
string data = "[";
for (i = 0; i < arr.size(); i++) {
if (!arr[i]) {
data += "null";
} else {
data += to_string(arr[i]->val);
}
if (i < arr.size() - 1) {
data += ",";
} else {
data += "]";
}
}
return data;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<TreeNode*> arr;
int i = 1;
int end = data.length() - 2;
bool neg;
int val = 0;
while (i <= end) {
if (data[i] == 'n') {
arr.push_back(nullptr);
i += 5;
continue;
}
neg = false;
if (data[i] == '-') {
neg = true;
i++;
}
val = 0;
while (i <= end && data[i] != ',') {
val = val * 10 + data[i] - '0';
i++;
}
if (neg) {
val = - val;
}
TreeNode* t = new TreeNode(val);
arr.push_back(t);
i++;
}
if (arr.empty()) {
return nullptr;
}
int pid = 0;
TreeNode* parent;
for (int i = 1; i < arr.size(); i++) {
parent = arr[pid];
if (i % 2 == 1) {
parent->left = arr[i];
} else {
parent->right = arr[i];
pid++;
while (!arr[pid]) {
pid++;
}
}
}
return arr[0];
}
};