// Encodes a tree to a single string. string serialize(TreeNode* root){ if (!root) return""; string ans = ""; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (!node) ans += "null,"; else ans += to_string(node->val) + ","; if (node) q.push(node->left); if (node) q.push(node->right); } return ans; }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ if (data == "") returnnullptr; queue<string> dataQ; string val; for (char c : data) { if (c == ',') dataQ.push(move(val)); else val += c; } auto getTreeNode = [](auto&& val) -> TreeNode* { return val == "null" ? nullptr : newTreeNode(stoi(val)); }; queue<TreeNode*> nodeQ; nodeQ.push(getTreeNode(dataQ.front())); dataQ.pop(); TreeNode* root = nodeQ.front(); while (!dataQ.empty()) { TreeNode* node = nodeQ.front(); nodeQ.pop(); node->left = getTreeNode(dataQ.front()); dataQ.pop(); node->right = getTreeNode(dataQ.front()); dataQ.pop(); if (node->left) nodeQ.push(node->left); if (node->right) nodeQ.push(node->right); } // 也可以用 vector<string> dataArray 代替 queue<string> dataQ // TreeNode* root = dataArray[0]; // for (int i = 1; i < dataArray.size() - 1; i += 2) { // TreeNode* node = q.front(); q.pop(); // node->left = getTreeNode(dataArray[i]); // node->right = getTreeNode(dataArray[i + 1]); // if (node->left) q.push(node->left); // if (node->right) q.push(node->right); // } return root; } };
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
// Encodes a tree to a single string. string serialize(TreeNode* root){ string ans; serializeDfs(root, ans); return ans; }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ queue<string> dataArray; string val; for (char c : data) { if (c == ',') dataArray.push(move(val)); else val += c; } returndeserializeDfs(dataArray); } };
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));