-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize_deserialize_binary_tree.cpp
More file actions
70 lines (58 loc) · 1.83 KB
/
Copy pathserialize_deserialize_binary_tree.cpp
File metadata and controls
70 lines (58 loc) · 1.83 KB
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
/**
* 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==nullptr) return "X,";
string leftSubtree = serialize(root->left);
string rightSubtree = serialize(root->right);
return to_string(root->val) +"," + leftSubtree + rightSubtree;
}
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
TreeNode* deserializeHelper(std::queue<string>& nodes)
{
if(nodes.size()==0){
return nullptr;
}
string element = nodes.front();
nodes.pop();
if(element=="X") return nullptr;
TreeNode* currentNode = new TreeNode(stoi(element));
currentNode->left = deserializeHelper(nodes);
currentNode->right = deserializeHelper(nodes);
return currentNode;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
std::queue<string> nodes;
std::cout<<"Print data: "<<data<<std::endl;
data.erase(data.size()-1);
std::vector<string> elements = split(data,',');
for(auto x: elements)
{
nodes.push(x);
}
return deserializeHelper(nodes);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));