###题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 ###代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
char* Serialize(TreeNode *root) {//bfs
string ans;
if (root != NULL) {
queue<TreeNode*> que;
que.push(root);
TreeNode* cur;
while (!que.empty()) {
cur = que.front();
que.pop();
if (cur == NULL) {
ans += '#';
} else {
if (ans.size() > 0 && ans[ans.size() - 1] != ' ' && ans[ans.size() - 1] != '#') {
ans += ' ';
}
ans += to_string(cur->val);
que.push(cur->left);
que.push(cur->right);
}
}
}
char *result = new char[ans.size() + 1];
for (int i = 0; i < ans.size(); ++i) {
result[i] = ans[i];
}
result[ans.size()] = ' ';
return result;
}
TreeNode* Deserialize(char *str) {//bfs
TreeNode* root = NULL;
if (str[0] != ' ') {
queue<TreeNode*> que;
int s = 0;
root = newNode(str, s);
que.push(root);
TreeNode* cur;
while (str[s] != ' ') {
cur = que.front();
que.pop();
if (isdigit(str[s]) || str[s++] == ' ') {
TreeNode* left = newNode(str, s);
cur->left = left;
que.push(left);
}
if (str[s] != ' ' && (isdigit(str[s]) || str[s++] == ' ')) {
TreeNode* right = newNode(str, s);
cur->right = right;
que.push(right);
}
}
}
return root;
}
TreeNode* newNode(char *str, int &s) {
string num;
while (str[s] != ' ' && str[s] != ' ' && str[s] != '#') {
num += str[s];
++s;
}
return new TreeNode(stoi(num));
}
};