题意
题解
BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static std::vector<std::string> split(std::string str, char c) {
vector<string> res;
int start = 0, pos;
pos = str.find(',', start);
while (pos != -1) {
res.push_back(str.substr(start, pos - start));
start = pos + 1;
pos = str.find(',', start);
}
if (pos != -1) res.push_back(str.substr(start, str.size() - pos));
return res;
}
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (root == nullptr) return "";
std::string res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node != nullptr) {
res += to_string(node->val) + ",";
q.push(node->left);
q.push(node->right);
} else {
res += "null,";
}
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<string> split_data = split(data, ',');
if (split_data.empty()) return nullptr;
queue<TreeNode*> q;
int index = 0;
TreeNode* root = new TreeNode(stoi(split_data[index++]));
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (split_data[index] != "null") {
node->left = new TreeNode(stoi(split_data[index]));
q.push(node->left);
}
index++;
if (split_data[index] != "null") {
node->right = new TreeNode(stoi(split_data[index]));
q.push(node->right);
}
index++;
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));