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