category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

297. Serialize and Deserialize Binary Tree

string serialize(TreeNode* root) {
        ostringstream out;
        pre(root, out);
        return out.str();
    }

    TreeNode* deserialize(string data) {
        istringstream in(data);
        return fun(in);
    }

    void pre(TreeNode* root, ostringstream& out) {
        if (root == nullptr) {
            out << "# ";
        }
        else {
            out << root->val << ' ';
            pre(root->left, out);
            pre(root->right, out);
        }
    }
    TreeNode* fun(istringstream& data) {
        string val;
        data >> val;

        if (val == "#")
            return nullptr;

        TreeNode* root = new TreeNode(stoi(val), fun(data), fun(data));
        return root;
    }