forked from ankurdcruz/CPP-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializeDeserializeBST.cpp
More file actions
54 lines (50 loc) · 1.41 KB
/
serializeDeserializeBST.cpp
File metadata and controls
54 lines (50 loc) · 1.41 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
//question link: https://leetcode.com/problems/serialize-and-deserialize-bst/
//code:
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root == NULL) {
return "";
}
string left = serialize(root->left);
string right = serialize(root->right);
string curr = to_string(root->val);
return curr+'x'+left+'x'+right;
}
TreeNode* addToBST(TreeNode*root, int data) {
TreeNode* currNode = new TreeNode(data);
if(root == NULL) {
return currNode;
}
if(data >= root->val) {
root->right = addToBST(root->right, data);
} else {
root->left = addToBST(root->left, data);
}
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* root = NULL;
string currData = "";
for(char ch: data) {
if(ch == 'x' && currData != "") {
int val = stoi(currData);
root = addToBST(root, val);
currData = "";
} else if(ch != 'x') {
currData = currData + ch;
}
}
return root;
}
};