/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: string s; // 用前序遍历 void ser(TreeNode* root, string& s) { if(root==nullptr) { s+='#'; s+=','; return; } s+=to_string(root->val); s+=','; ser(root->left,s); ser(root->right,s); } char* Serialize(TreeNode *root) { ser(root,s); return const_cast<char*>(s.c_str()); } TreeNode* Deserialize(char *str) { string data(str); // cout<<"s: "<<data<<endl; int index = 0; return des(data,index); } TreeNode* des(string& s, int& index) { if(index==s.size() || index>s.size()) { return nullptr; } if(s[index]=='#') { index++; index++; return nullptr; } int sum = 0; while(s[index]!=',') { sum=sum*10+s[index]-'0'; index++; } index++; TreeNode* root = new TreeNode(sum); root->left=des(s,index); root->right=des(s,index); return root; } };