-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path61.cpp
More file actions
81 lines (71 loc) · 1.54 KB
/
61.cpp
File metadata and controls
81 lines (71 loc) · 1.54 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
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
TreeNode() {}
};
TreeNode *newTree() {
TreeNode *node = new TreeNode;
int x;
cin >> x;
if (!x)node = NULL;
else {
node->val = x;
node->left = newTree();
node->right = newTree();
}
return node;
}
void preOrder(TreeNode *pRoot)
{
if (pRoot)
{
cout << pRoot->val << " ";
preOrder(pRoot->left);
preOrder(pRoot->right);
}
}
char* Serialize(TreeNode *root) {
if(!root)return "#";
string s=to_string(root->val);
s.push_back(',');
char *left = Serialize(root->left);
char *right = Serialize(root->right);
char *res = new char[strlen(left) + strlen(right) + s.size()];
strcpy(res, s.c_str());
strcat(res, left);
strcat(res, right);
return res;
}
TreeNode* decode(char *&str) {
if(*str=='#'){
str++;
return NULL;
}
int num = 0;
while(*str != ',')
num = num*10 + (*(str++)-'0');
str++;
TreeNode *root = new TreeNode(num);
root->left = decode(str);
root->right = decode(str);
return root;
}
TreeNode* Deserialize(char *str) {
return decode(str);
}
int main() {
ios::sync_with_stdio(false);
TreeNode *root = NULL;
root = newTree();
cout<<Serialize(root)<<endl;
TreeNode * res = Deserialize(Serialize(root));
preOrder(res);
return 0;
}