-
Notifications
You must be signed in to change notification settings - Fork 0
/
dailycoding003.cpp
65 lines (50 loc) · 1.36 KB
/
dailycoding003.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
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
struct Node {
string val;
struct Node *left, *right;
};
Node* newNode(string val) {
Node* temp = new Node;
temp->val = val;
temp->left = temp->right = NULL;
return temp;
}
string serialize(Node *root) {
if (root == NULL) {
return "NULL";
}
return root->val + "," + serialize(root->left) + "," + serialize(root->right);
}
Node* deserialize_rec(string &tree) {
string &treecpy = tree;
int pos = treecpy.find(",");
string val = treecpy.substr(0, pos);
treecpy = treecpy.substr(pos+1, treecpy.length()-1);
if (val == "NULL") return NULL;
Node *ret = newNode(val);
ret->left = deserialize_rec(treecpy);
ret->right = deserialize_rec(treecpy);
return ret;
}
Node* deserialize(string tree) {
string treecpy = tree;
return deserialize_rec(treecpy);
}
int main() {
Node *root = newNode("root");
root->left = newNode("left");
root->right = newNode("right");
root->left->left = newNode("left.left");
string serialized = serialize(root);
string encdec = serialize(deserialize(serialized));
if (serialized == serialize(deserialize(serialized))) {
cout << "Passed" << endl;
} else {
cout << "Failed" << endl;
}
return 0;
}