-
序列化
string serialize(TreeNode* root){ string res; dfs_s(root, res); return res; } void dfs_s(TreeNode* root, string &res) { if(!root) { res += "#,"; return; } res += to_string(root -> val) + ','; dfs_s(root -> left, res); dfs_s(root -> right, res); }
-
反序列化
TreeNode* deserialize(string data) { int u = 0; return dfs_d(data, u); } TreeNode* dfs_d(string data, int &u) { if(data[u] == '#') { u += 2; return nullptr; } int t = 0; bool is_minus = false; while(data[u] != ',') { if(data[u] == '-') is_minus = true; else t = t * 10 + data[u] - '0'; u ++; } u ++; if(is_minus) t = -t; auto root = new TreeNode(t); root -> left = dfs_d(data, u); root -> right = dfs_d(data, u); return root; }