-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_297_SerializeAndDeserializeABinaryTree.cpp
78 lines (61 loc) · 1.72 KB
/
_297_SerializeAndDeserializeABinaryTree.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
/* Source - https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int data;
TreeNode* left, *right;
TreeNode (int x) {
data = x;
left = right = NULL;
}
};
string serialize (TreeNode* root) {
if (root == NULL) return "#";
string left = serialize(root->left);
string right = serialize(root->right);
return to_string(root->data) + "*" + left + right;
}
TreeNode* deserializeUtil (string serialized, int &i) {
if (serialized[i] == '#') {
i++;
return NULL;
}
string val = "";
while(serialized[i] != '*') {
val += string(1, serialized[i]);
i++;
}
i++;
TreeNode* root = new TreeNode(stoi(val));
root->left = deserializeUtil(serialized, i);
root->right = deserializeUtil(serialized, i);
return root;
}
TreeNode* deserialize (string serialized) {
int i = 0;
return deserializeUtil(serialized, i);
}
void printInorder (TreeNode *root) {
if (root == NULL) return;
printInorder(root->left);
cout<<root->data<<" ";
printInorder(root->right);
}
int main()
{
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->left->right->left = new TreeNode(8);
root->left->right->right = new TreeNode(9);
root->right->right = new TreeNode(7);
string serialized = serialize(root);
cout<<"Tree serialized in a string: "<<serialized<<endl;
cout<<"Inorder of deserialized tree: ";
printInorder(deserialize(serialized));
cout<<endl;
}