-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathSerializeDeSerialize an arbitrary nodes tree.cpp
117 lines (76 loc) · 1.9 KB
/
SerializeDeSerialize an arbitrary nodes 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
SerializeDeSerialize an arbitrary nodes tree
*/
/*
solution: preorder traversal
O(n) time
*/
#include<iostream>
#include<vector>
using namespace std;
struct NODE {
int val;
vector<NODE*> vec;
NODE(int n) : val(n), vec() {}
};
void SerialInner(NODE* node, char*& p) {
itoa(node->val, p, 10);
p += strlen(p);
int num = node->vec.size();
itoa(num, p, 10);
p += strlen(p);
if (node->vec.size() == 0) return;
for (vector<NODE*>::iterator it = node->vec.begin(); it != pNode->vec.end(); it++) {
SerialInner(*it, p);
}
}
char* Serialize(NODE* root, char mem[]) {
if (NULL == mem || NULL == root) return NULL;
char* p = mem;
SerialInner(root, p);
p++;
*p='\0';
return mem;
}
int Proc(const char*& p) {
int val = 0;
while (*p >= '0' && *p <= '9' && *p!=' ') {
val = 10 * val + *p++ - '0';
}
p++;
return val;
}
NODE *DeserialInner(const char*& p) {
int val = Proc(p);
NODE *sresult = new NODE(val);
val = Proc(p);
int childnum = val;
for (int i = 0; i < childnum; ++i) {
result->vec.push_back(DeserialInner(p));
}
return result;
}
NODE *DeSerialize(const char mem[]) {
if (NULL == mem) return NULL;
const char* p = mem;
return DeserialInner(p);
}
int main() {
NODE *root1 = new NODE(3);
NODE *p1 = new NODE(1);
NODE *p2 = new NODE(2);
NODE *p3 = new NODE(4);
root1->vec.push_back(p1);
root1->vec.push_back(p2);
root1->vec.push_back(p3);
char str[] = "";
Serialize(root1, str);
cout<<str<<endl;
const char mem1[] = "3 3 1 0 2 0 4 0";
NODE *root = DeSerialize(mem1);
cout<<root->val<<endl;
for (vector<NODE*>::iterator it = root->vec.begin(); it != root->vec.end(); it++) {
cout<<(*it)->val<<endl;
}
return 0;
}