leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0297.cpp (979B)
0 class Codec {
1 public:
2 string serialize(TreeNode *root) {
3 ostringstream out;
4 serialize(root, out);
5 return out.str();
6 }
8 TreeNode *deserialize(string data) {
9 istringstream in(data);
10 return deserialize(in);
11 }
13 private:
14 void serialize(TreeNode *root, ostringstream &out) {
15 stack<TreeNode *> st;
17 st.push(root);
18 while (!st.empty()) {
19 TreeNode *root = st.top();
20 st.pop();
21 if (!root)
22 out << "# ";
23 else {
24 out << root->val << ' ';
25 st.push(root->right);
26 st.push(root->left);
27 }
28 }
29 }
31 TreeNode *deserialize(istringstream &in) {
32 string val;
33 in >> val;
34 if (val == "#") return nullptr;
35 TreeNode *root = new TreeNode(stoi(val));
36 root->left = deserialize(in);
37 root->right = deserialize(in);
38 return root;
39 }
40 };