树的序列化和反序列化
序列化二叉树
http://www.nowcoder.com/questionTerminal/cf7e25aa97c04cc1a68c8f040e71fb84
解题思路:
序列化没什么好讲的就是前序遍历
然后反序列化生成树类似于树的复制。从父节点到子节点递归。
知道遇到‘#’,返回空
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: string s; int j=0; void Srtial(TreeNode *root) { if(root==NULL) { s+="#!"; return ; } s+=to_string(root->val); s+="!"; Srtial(root->left); Srtial(root->right); } char* Serialize(TreeNode *root) { Srtial(root); return (char *)s.data(); } TreeNode* Deserialize(char *str) { s=str; return Deserial(); } TreeNode* Deserial() { if(s.size()==0) return NULL; if(s[j]=='!') { j++; if(j>=s.size()) return NULL; } if(s[j]=='#'){ j++; return NULL; } int num=0; while(s[j]>='0' && s[j]<='9'){ num=num*10+s[j++]-'0';} TreeNode *root=new TreeNode(num); root->left=Deserial(); root->right=Deserial(); return root; } };