Skip to content

Commit 1697406

Browse files
Create Serialize and Deserialize Binary Tree.cpp
1 parent 771a46d commit 1697406

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
2+
3+
class Codec {
4+
public:
5+
string serialize(TreeNode* root) {
6+
ostringstream temp;
7+
ToString(root, temp);
8+
return temp.str();
9+
}
10+
11+
TreeNode* deserialize(string data) {
12+
istringstream temp(data);
13+
return ToStructure(temp);
14+
}
15+
16+
private:
17+
void ToString(TreeNode* root, ostringstream& temp) {
18+
if (root == NULL) {
19+
temp << "N ";
20+
return;
21+
}
22+
temp << root->val << " ";
23+
ToString(root->left, temp);
24+
ToString(root->right, temp);
25+
}
26+
27+
TreeNode* ToStructure(istringstream& temp) {
28+
string value = "";
29+
temp >> value;
30+
if (value == "N") {
31+
return NULL;
32+
}
33+
TreeNode* root = new TreeNode(stoi(value));
34+
root->left = ToStructure(temp);
35+
root->right = ToStructure(temp);
36+
return root;
37+
}
38+
};

0 commit comments

Comments
 (0)