File tree Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Expand file tree Collapse file tree 1 file changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 29 ms
2
+ class Codec {
3
+ public:
4
+
5
+ // Encodes a tree to a single string.
6
+ string serialize (TreeNode* root) {
7
+ if (!root)
8
+ return " " ;
9
+ queue<TreeNode*> Q;
10
+ Q.push (root);
11
+ string s;
12
+ int len;
13
+ while (!Q.empty ())
14
+ {
15
+ TreeNode* t = Q.front ();
16
+ Q.pop ();
17
+
18
+ if (t)
19
+ {
20
+ s += to_string (t->val ) + ' ,' ;
21
+ len = s.size ();
22
+ }
23
+
24
+ else
25
+ s += " #," ;
26
+
27
+ if (t)
28
+ {
29
+ Q.push (t->left );
30
+ Q.push (t->right );
31
+ }
32
+ }
33
+ s = s.substr (0 , len-1 );
34
+ return s;
35
+ }
36
+
37
+ // Decodes your encoded data to tree.
38
+ TreeNode* deserialize (string data) {
39
+ vector<string> S;
40
+ if (data.size ()<=0 )
41
+ return NULL ;
42
+
43
+ for (int i=0 ;i<data.size ();i++)
44
+ {
45
+ string s;
46
+ while (i<data.size () && data[i] != ' ,' )
47
+ s += data[i++];
48
+ S.push_back (s);
49
+ }
50
+ TreeNode* root;
51
+ int i = 0 ;
52
+ queue<TreeNode*> Q;
53
+ root = new TreeNode (stoi (S[i++]));
54
+ Q.push (root);
55
+ while (!Q.empty () && i<S.size ())
56
+ {
57
+ TreeNode* t = Q.front ();
58
+ Q.pop ();
59
+
60
+ if (S[i] != " #" )
61
+ {
62
+ t->left = new TreeNode (stoi (S[i++]));
63
+ Q.push (t->left );
64
+ }
65
+ else
66
+ i++;
67
+
68
+ if (i<S.size () && S[i] != " #" )
69
+ {
70
+ t->right = new TreeNode (stoi (S[i++]));
71
+ Q.push (t->right );
72
+ }
73
+ else
74
+ i++;
75
+ }
76
+
77
+ return root;
78
+ }
79
+ };
You can’t perform that action at this time.
0 commit comments