-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter4-binary-tree.cpp
93 lines (80 loc) · 1.72 KB
/
chapter4-binary-tree.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
// My implementation for binary tree.
#include <string>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val): val(_val), left(nullptr), right(nullptr) {};
};
// One of the (de)serialization method I wrote.
// Here is a serialization sample for this piece of code: {3,1,#,#,10,6,#,#,11,#,14,#,#}
// 3
// / \
// 1 10
// / \
// 6 11
// \
// 14
class BinaryTreeSerializer {
public:
string serialize(TreeNode *root) {
string res = "{";
// preorder traversal
serializeTraversal(root, res);
res[res.length() - 1] = '}';
return res;
};
TreeNode *deserialize(string s) {
vector<string> data;
int i, j, len;
len = (int)s.length();
i = 1;
while (true) {
j = i + 1;
while (s[j] != ',' && s[j] != '}') {
++j;
}
data.push_back(s.substr(i, j - i));
i = j + 1;
if (i >= len) {
break;
}
}
int iter = 0;
TreeNode *root = nullptr;
// preorder traversal
deserializeTraversal(data, root, iter);
return root;
};
private:
static char ss[10];
void serializeTraversal(TreeNode *root, string &res) {
if (root == nullptr) {
res += "#,";
} else {
sprintf(ss, "%d", root->val);
res += string(ss);
res.push_back(',');
serializeTraversal(root->left, res);
serializeTraversal(root->right, res);
}
};
void deserializeTraversal(vector<string> &data, TreeNode *&root, int &iter) {
++iter;
if (data[iter - 1] == "#") {
root = nullptr;
} else {
int val;
sscanf(data[iter - 1].c_str(), "%d", &val);
root = new TreeNode(val);
deserializeTraversal(data, root->left, iter);
deserializeTraversal(data, root->right, iter);
}
};
};
int main()
{
return 0;
}