活跃农民
- 积分
- 430
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-4-4
- 最后登录
- 1970-1-1
|
- #include <iostream>
- #include <vector>
- #include <string>
- #include <stack>
- using namespace std;
- struct TreeNode {
- int val;
- vector<TreeNode*> children = {};
- TreeNode(int _val) {
- val = _val;
- }
- };
- TreeNode* deserialize(string in) {
- TreeNode* root = nullptr;
- TreeNode* parent = nullptr;
- stack<TreeNode*> s;
- int pos = 0;
- while (pos < in.size()) {
- if (in[pos] == '(') {
- pos++;
- TreeNode* node = new TreeNode(in[pos] - '0');
- if (!parent) root = node;
- else parent->children.push_back(node);
- s.push(node);
- parent = node;
- } else if (in[pos] == ')') {
- s.pop();
- if (!s.empty()) parent = s.top();
- }
- pos++;
- }
- return root;
- }
- void serialize(TreeNode* root, string& out) {
- if (root) {
- out.push_back('(');
- out+=to_string(root->val);
- for (TreeNode* child : root->children) {
- serialize(child, out);
- }
- out.push_back(')');
- }
- }
- int main() {
- string in = "(1(2)(3(5)(6))(4(7)))";
- cout << in << endl;
- TreeNode* root = deserialize(in);
- cout << root->val << endl;
- string out = "";
- serialize(root, out);
- cout << out << endl;
- return 0;
- }
复制代码 |
|