File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 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+ public:
12+ string serialize (TreeNode* root) {
13+ ostringstream out;
14+ serializeHelper (root, out);
15+ return out.str ();
16+ }
17+
18+ // Decodes your encoded data to tree.
19+ TreeNode* deserialize (string data) {
20+ if (data.empty ()) {
21+ return NULL ;
22+ }
23+ istringstream in (data);
24+ queue<int > q;
25+ string val;
26+ while (in >> val) {
27+ q.push (stoi (val));
28+ }
29+ return deserializeHelper (q, INT_MIN, INT_MAX);
30+ }
31+ private:
32+ void serializeHelper (TreeNode* root, ostringstream& out) {
33+ if (root == NULL )
34+ return ;
35+ out << root -> val << " " ;
36+ serializeHelper (root->left , out);
37+ serializeHelper (root->right , out);
38+ }
39+ TreeNode* deserializeHelper (queue<int >& q, int lower, int upper) {
40+ if (q.empty ())
41+ return NULL ;
42+ int cur = q.front ();
43+ if (cur < lower || cur > upper) {
44+ return NULL ;
45+ }
46+ TreeNode* root = new TreeNode (cur);
47+ q.pop ();
48+ root -> left = deserializeHelper (q, lower, cur);
49+ root -> right = deserializeHelper (q, cur, upper);
50+ return root;
51+ }
52+ };
53+
54+ // Your Codec object will be instantiated and called as such:
55+ // Codec codec;
56+ // codec.deserialize(codec.serialize(root));
You can’t perform that action at this time.
0 commit comments