File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
2
+
3
+ class Codec {
4
+ public:
5
+ string serialize (TreeNode* root) {
6
+ ostringstream temp;
7
+ ToString (root, temp);
8
+ return temp.str ();
9
+ }
10
+
11
+ TreeNode* deserialize (string data) {
12
+ istringstream temp (data);
13
+ return ToStructure (temp);
14
+ }
15
+
16
+ private:
17
+ void ToString (TreeNode* root, ostringstream& temp) {
18
+ if (root == NULL ) {
19
+ temp << " N " ;
20
+ return ;
21
+ }
22
+ temp << root->val << " " ;
23
+ ToString (root->left , temp);
24
+ ToString (root->right , temp);
25
+ }
26
+
27
+ TreeNode* ToStructure (istringstream& temp) {
28
+ string value = " " ;
29
+ temp >> value;
30
+ if (value == " N" ) {
31
+ return NULL ;
32
+ }
33
+ TreeNode* root = new TreeNode (stoi (value));
34
+ root->left = ToStructure (temp);
35
+ root->right = ToStructure (temp);
36
+ return root;
37
+ }
38
+ };
You can’t perform that action at this time.
0 commit comments