(1) 先序遍历构造字符串
(2) 确定一个数组下标根据字符串按序还原树结构
/* 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 dfs(TreeNode* p){ if(p==NULL){ s+="#"; return; } s+=to_string(p->val); s+="!"; dfs(p->left); dfs(p->right); } char* Serialize(TreeNode *root) { dfs(root); return (char*)s.data(); } int idx=0; TreeNode* Deserialize(char *str) { if(str[idx]==0) return NULL; if(str[idx]=='#'){ idx++; return NULL; } int val=0; while(str[idx]>='0'&&str[idx]<='9'){ val = val*10+str[idx]-'0'; idx++; } idx++; TreeNode* p = new TreeNode(val); p->left = Deserialize(str); p->right = Deserialize(str); return p; } };