Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long long;
- struct Node {
- ll val;
- Node *left;
- Node *right;
- ~Node()
- {
- delete left;
- delete right;
- }
- };
- // all symbols
- // [0, val] means number
- // [1, x] means left bracket
- // [2, x] means right bracket
- // [3, x] means OEF
- using a2l = array<ll, 2>;
- Node *deserialize(const string &s)
- {
- ll idx = 0;
- auto lookup_sym = [&](bool consume) -> a2l {
- a2l ret;
- ll nid = idx;
- while (nid < s.size() && s[nid] == ' ')
- ++nid;
- if (nid == s.size()) {
- ret = {3, 0};
- } else if (s[nid] == ')') {
- ret = {2, 0}, ++nid;
- } else if (s[nid] == '(') {
- ret = {1, 0}, ++nid;
- } else {
- ll val = 0;
- while (nid < s.size() && s[nid] >= '0' && s[nid] <= '9') {
- val = val * 10 + s[nid] - '0';
- nid++;
- }
- ret = {0, val};
- }
- if (consume)
- idx = nid;
- return ret;
- };
- /*
- for (auto x = lookup_sym(true); x[0] != 3; x = lookup_sym(true)) {
- cerr << "symbol: " << x[0] << " val: " << x[1] << " pos: " << idx << endl;
- }
- return nullptr;
- */
- function<Node *()> read_subtree = [&]() {
- a2l sym = lookup_sym(true);
- assert(sym[0] == 1);
- sym = lookup_sym(true);
- Node *n = nullptr;
- if (sym[0] == 2) {
- return n;
- } else {
- assert(sym[0] == 0);
- n = new Node;
- n->val = sym[1];
- n->left = read_subtree(); // consume left child
- n->right = read_subtree(); // consume right child
- }
- sym = lookup_sym(true); // consume right bracket
- assert(sym[0] == 2);
- return n;
- };
- return read_subtree();
- }
- /*
- 4
- 2 6
- 1 3 null 8
- */
- int main()
- {
- string s = "(4 (2 (1 () ()) (3 () ())) (6 () (85 () ())))";
- Node *n = deserialize(s);
- assert(n->val == 4);
- assert(n->left->val == 2);
- assert(n->left->left->val == 1);
- assert(n->left->right->val == 3);
- assert(n->left->left->left == nullptr);
- assert(n->left->left->right == nullptr);
- assert(n->left->right->left == nullptr);
- assert(n->left->right->right == nullptr);
- assert(n->right->val == 6);
- assert(n->right->left == nullptr);
- assert(n->right->right->val == 85);
- assert(n->right->right->left == nullptr);
- assert(n->right->right->right == nullptr);
- delete n;
- return 0;
- }
Add Comment
Please, Sign In to add comment