1+ /* *
2+ * Definition for a binary tree node.
3+ * struct TreeNode {
4+ * int val;
5+ * TreeNode *left;
6+ * TreeNode *right;
7+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+ * };
9+ */
10+ class Codec {
11+ private:
12+ char delimiter = ' ' ;
13+ 14+ // PreOrder
15+ void dfs (TreeNode* root, string& s) {
16+ if (root == NULL ) return ;
17+ 18+ s.append (to_string (root->val ) + delimiter);
19+ 20+ dfs (root->left , s);
21+ dfs (root->right , s);
22+ }
23+ 24+ vector<int > stringToVector (string s) {
25+ vector<int > res;
26+ int n = s.size ();
27+ int i = 0 ;
28+ string tmp = " " ;
29+ 30+ while (i < n) {
31+ 32+ while (i < n && s[i] != delimiter) {
33+ tmp += s[i];
34+ i++;
35+ }
36+ 37+ res.push_back (stoi (tmp));
38+ tmp.erase ();
39+ i++;
40+ }
41+ 42+ return res;
43+ }
44+ 45+ TreeNode* createBST (vector<int > nums, int start, int end) {
46+ if (start > end) return NULL ;
47+ 48+ TreeNode* root = new TreeNode (nums[start]);
49+ 50+ int index;
51+ 52+ for (index = start; index <= end; ++index) {
53+ if (nums[index] > nums[start]) break ;
54+ }
55+ 56+ root->left = createBST (nums, start + 1 , index - 1 );
57+ root->right = createBST (nums, index, end);
58+ 59+ return root;
60+ }
61+ public:
62+ 63+ // Encodes a tree to a single string.
64+ string serialize (TreeNode* root) {
65+ if (root == NULL ) return " " ;
66+ string s = " " ;
67+ dfs (root, s);
68+ return s;
69+ }
70+ 71+ // Decodes your encoded data to tree.
72+ TreeNode* deserialize (string data) {
73+ if (data == " " ) return NULL ;
74+ vector<int > nums = stringToVector (data);
75+ 76+ return createBST (nums, 0 , nums.size () - 1 );
77+ }
78+ };
79+ 80+ // Your Codec object will be instantiated and called as such:
81+ // Codec* ser = new Codec();
82+ // Codec* deser = new Codec();
83+ // string tree = ser->serialize(root);
84+ // TreeNode* ans = deser->deserialize(tree);
85+ // return ans;
0 commit comments