-
Notifications
You must be signed in to change notification settings - Fork 0
/
Daily_Coding_Problem-03.cpp
97 lines (87 loc) · 2.47 KB
/
Daily_Coding_Problem-03.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
/* MARK: - SOLUTION ✨ */
#include "Daily_Coding_Problem.h"
// * Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// MARK: - Solution
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (root == NULL) return "";
queue<TreeNode*> q;
q.push(root);
string result = "";
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node == NULL) {
result += "null,";
continue;
}
result += to_string(node->val) + ",";
q.push(node->left);
q.push(node->right);
}
return result;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data == "") return NULL;
vector<string> nodes;
stringstream ss(data);
string node;
while (getline(ss, node, ',')) {
nodes.push_back(node);
}
TreeNode* root = new TreeNode(stoi(nodes[0]));
queue<TreeNode*> q;
q.push(root);
int i = 1;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (nodes[i] != "null") {
node->left = new TreeNode(stoi(nodes[i]));
q.push(node->left);
}
i++;
if (nodes[i] != "null") {
node->right = new TreeNode(stoi(nodes[i]));
q.push(node->right);
}
i++;
}
return root;
}
};
int main() {
Codec codec;
TreeNode* root = new TreeNode(2);
root->left = new TreeNode(1);
root->right = new TreeNode(3);
string serialized = codec.serialize(root);
TreeNode* deserialized = codec.deserialize(serialized);
printf("Serialized: %s \n", deserialized->left->val == 1 ? "✅" : "❌");
printf("Deserialized: %s \n", deserialized->right->val == 3 ? "✅" : "❌");
assert(deserialized->val == 2);
assert(deserialized->left->val == 1);
assert(deserialized->right->val == 3);
return 0;
}
// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
/* MARK: - TESTS ✨ */
/*
* 2
* / \
* 1 3
*/