leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0297.cpp (979B)


      1 class Codec {
      2   public:
      3     string serialize(TreeNode *root) {
      4         ostringstream out;
      5         serialize(root, out);
      6         return out.str();
      7     }
      8 
      9     TreeNode *deserialize(string data) {
     10         istringstream in(data);
     11         return deserialize(in);
     12     }
     13 
     14   private:
     15     void serialize(TreeNode *root, ostringstream &out) {
     16         stack<TreeNode *> st;
     17 
     18         st.push(root);
     19         while (!st.empty()) {
     20             TreeNode *root = st.top();
     21             st.pop();
     22             if (!root)
     23                 out << "# ";
     24             else {
     25                 out << root->val << ' ';
     26                 st.push(root->right);
     27                 st.push(root->left);
     28             }
     29         }
     30     }
     31 
     32     TreeNode *deserialize(istringstream &in) {
     33         string val;
     34         in >> val;
     35         if (val == "#") return nullptr;
     36         TreeNode *root = new TreeNode(stoi(val));
     37         root->left = deserialize(in);
     38         root->right = deserialize(in);
     39         return root;
     40     }
     41 };