解法一:先序遍历
注意其中的ostringstream 和 istringstream 的用法,
字符串转int stoi
// Recursion
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
serialize(root, out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return deserialize(in);
}
private:
void serialize(TreeNode *root, ostringstream &out) {
if (root) {
out << root->val << ' ';
serialize(root->left, out);
serialize(root->right, out);
} else {
out << "# ";
}
}
TreeNode* deserialize(istringstream &in) {
string val;
in >> val;
if (val == "#") return nullptr;
TreeNode *root = new TreeNode(stoi(val));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
};
解法二:利用队列,层次遍历
注意 int->string 用to_string
string -> int 用stoi
/**
* Definition for a binary tree node.
* 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) {
queue<TreeNode*> q;
q.push(root);
string ans = "";
while(!q.empty()){
TreeNode* cur = q.front();
q.pop();
if(cur != NULL){
ans += to_string(cur->val) + " ";
q.push(cur->left);
q.push(cur->right);
}
else{
ans += "NULL ";//这里必须要有空格!!!!!
}
}
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
vector<TreeNode*> nodes;
string tmp;
while(in>>tmp){
if(tmp != "NULL"){
nodes.push_back(new TreeNode(stoi(tmp)));
}
else{
nodes.push_back(NULL);
}
}
int pos = 0, offset = 1;
while(offset < nodes.size()){
if(nodes[pos] != NULL){
nodes[pos]->left = nodes[offset++];
if(offset < nodes.size()) nodes[pos]->right = nodes[offset++];
}
pos += 1;
}
return nodes[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
网友评论