```cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classCodec { public: string s;
voids_dfs(TreeNode* root){ if (!root) { s += "#,"; return; }
s += to_string(root->val) + ','; s_dfs(root->left); s_dfs(root->right); } string serialize(TreeNode* root){ if (!root) return s; s_dfs(root); return s; }
TreeNode* d_dfs(string& s, int& u){ if (s[u] == '#') { u += 2; returnnullptr; } // 判断负号 bool is_minus = false; if (s[u] == '-') is_minus = true, u ++ ; int k = u; int val = 0; while (k < s.size() && s[k] != ',') val = val * 10 + (s[k ++ ] - '0'); if (is_minus) val = -val; k ++ ; u = k; auto root = newTreeNode(val); root->left = d_dfs(s, u); root->right = d_dfs(s, u); return root; }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ if (data.empty()) returnnullptr; cout << data << endl; int u = 0; returnd_dfs(data, u); } };