forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
123 lines (97 loc) · 2.79 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/// Source : https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
/// Author : liuyubobobo
/// Time : 2018-09-17
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
/// BFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)
return "[null]";
string ret = "[";
queue<TreeNode*> q;
q.push(root);
ret += to_string(root->val);
while(!q.empty()){
TreeNode* cur = q.front();
q.pop();
if(cur->left){
ret += "," + to_string(cur->left->val);
q.push(cur->left);
}
else
ret += ",null";
if(cur->right){
ret += "," + to_string(cur->right->val);
q.push(cur->right);
}
else
ret += ",null";
}
return ret + "]";
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<string> vec = get_vector(data);
if(vec.size() == 0 || (vec.size() == 1 && vec[0] == "null"))
return NULL;
TreeNode* root = new TreeNode(atoi(vec[0].c_str()));
queue<TreeNode*> q;
q.push(root);
int index = 1;
while(!q.empty()){
TreeNode* cur = q.front();
q.pop();
assert(vec.size() - index >= 2);
if(vec[index] != "null"){
cur->left = new TreeNode(atoi(vec[index].c_str()));
q.push(cur->left);
}
index ++;
if(vec[index] != "null"){
cur->right = new TreeNode(atoi(vec[index].c_str()));
q.push(cur->right);
}
index ++;
}
return root;
}
private:
vector<string> get_vector(const string& data){
string s = data.substr(1, data.size() - 2) + ",";
vector<string> res;
int i = 0;
while(i < s.size()){
int comma = s.find(',', i);
res.push_back(s.substr(i, comma - i));
i = comma + 1;
}
return res;
}
};
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(5);
string s = Codec().serialize(root);
cout << s << endl;
TreeNode* x = Codec().deserialize(s);
cout << Codec().serialize(x) << endl;
return 0;
}