Concise C++ 19ms solution beating 99.4%
Sharing my solution which doesn't have to parse string for comma at all!\n\nThe encoding schema is preorder of BST, and to decode this we can use the same preor
Sharing my solution which doesn't have to parse string for comma at all!\n\nThe encoding schema is preorder of BST, and to decode this we can use the same preorder traversal to do it in one pass with recursion in O(n) time.\n\nTo minimize the memory, I used binary format instead of ascii format for each integer, just burn those int into 4 chars will save you a lot!!!\n\nReally if using ASCII numbers you are paying a lot of penalty memory for integers over 4 digit long and parsing comma is just as painful.\n\n```\nclass Codec {\npublic:\n\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        string order;\n        inorderDFS(root, order);\n        return order;\n    }\n    \n    inline void inorderDFS(TreeNode* root, string& order) {\n        if (!root) return;\n        char buf[4];\n        memcpy(buf, &(root->val), sizeof(int)); //burn the int into 4 chars\n        for (int i=0; i<4; i++) order.push_back(buf[i]);\n        inorderDFS(root->left, order);\n        inorderDFS(root->right, order);\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) {\n        int pos = 0;\n        return reconstruct(data, pos, INT_MIN, INT_MAX);\n    }\n    \n    inline TreeNode* reconstruct(const string& buffer, int& pos, int minValue, int maxValue) {\n        if (pos >= buffer.size()) return NULL; //using pos to check whether buffer ends is better than using char* directly.\n        \n        int value;\n        memcpy(&value, &buffer[pos], sizeof(int));\n        if (value < minValue || value > maxValue) return NULL;\n        \n        TreeNode* node = new TreeNode(value);\n        pos += sizeof(int);\n        node->left = reconstruct(buffer, pos, minValue, value);\n        node->right = reconstruct(buffer, pos, value, maxValue);\n        return node;\n    }\n};\n```
[]