Small and Simple Code in C++ with O(N) time complexity
Do the dry run to understand\nexample:\n1 ( 2 (4) (5) ) (3 (6) ( 7 (8) (9) ) )\n1 -> children 2 and 3\n2 -> children 4 and 5\n3 -> children 6 and 7\n7 -> childr
Do the dry run to understand\nexample:\n1 ( 2 (4) (5) ) (3 (6) ( 7 (8) (9) ) )\n1 -> children 2 and 3\n2 -> children 4 and 5\n3 -> children 6 and 7\n7 -> children 8 and 9\n```\nclass Codec {\npublic:\n\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        string str = "";\n        if(root == NULL) return str;\n        str = to_string(root->val) + "(" + serialize(root->left) + ")" + "(" + serialize(root->right) + ")";\n        return str;\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* decode(string &data, int &i) {\n        if(i < data.size() && data[i] == \'(\') i++;\n        if(i>=data.size() || data[i] == \')\') {\n            return NULL;\n        }\n        \n        int num = 0;\n        while(data[i] <= \'9\' && data[i] >= \'0\') {\n            num = num * 10 + (data[i] - \'0\');\n            i++;\n        }\n        \n        TreeNode* root = new TreeNode(num);\n        root->left = decode(data, i);\n        i++;\n        root->right = decode(data, i);\n        i++;\n        \n        return root;\n    }\n    \n    TreeNode* deserialize(string data) {\n        int i=0;\n        return decode(data, i);       \n    }\n};\n```
['Depth-First Search', 'Binary Search Tree', 'Recursion', 'C', 'C++']