序列化二叉树_牛客题霸_牛客网
char*传入,以 “!"分割,以"#"表示无
/*
struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:
void reserialize(TreeNode* root, string& str)
{if(root == NULL){str += "#";}else{str += to_string(root->val) + "!";reserialize(root->left, str);reserialize(root->right, str);}
}char* Serialize(TreeNode *root) { if(root == NULL) return "#"; string ret;reserialize(root, ret);char* charRet = new char[ret.length() + 1];strcpy(charRet, ret.c_str());charRet[ret.length()] = '\0';return charRet; }TreeNode* DeserializeFunction(char** str){if(**str == '#'){(*str)++;return NULL;}int val = 0;while(**str != '!' && **str != '\0'){val = val*10 +((**str) - '0');(*str)++;}TreeNode* root = new TreeNode(val);if(**str == '\0')return root;else(*str)++;root->left = DeserializeFunction(str); root->right = DeserializeFunction(str);return root;}TreeNode* Deserialize(char *str) {TreeNode* res = DeserializeFunction(&str);return res;}
};
. - 力扣(LeetCode)
//由root进入,使用str将字符串带出
void reserialize(TreeNode* root, string& str)
{if(root == nullptr){str += "None,";}else{str += to_string(root->val) + ",";reserialize(root->left, str);reserialize(root->right, str);}
}//将二叉树转化程字符串
string serialize(TreeNode* root)
{string ret;reserialize(root, ret);return ret;
}TreeNode* rdeserialize(list<string>& dataArray)
{if(dataArray.front() == "None"){dataArray.erase(dataArray.begin());return nullptr;}TreeNode* root = new TreeNode(stoi(dataArray.front()));dataArray.erase(dataArray.begin());root->left = rdeserialize(dataArray);root->right = rdeserialize(dataArray);return root;
}
TreeNode* deserialize(string data)
{list<string> dataArray;string str;for(auto& ch : data){if(ch == ','){dataArray.push_back(str);str.clear();}else{str.push_back(ch);}}if(!str.empty()){dataArray.push_back(str);str.clear();}return rdeserialize(dataArray);
}