449. 序列化和反序列化二叉搜索树

文章目录

  • 题意
  • 思路
  • 代码

题意

题目链接
一棵树如果编码成string,然后解码回来。

思路

使用BFS,按节点保存起来,使用-1标识空指针;没有重复节点,直接模拟就好了;虽然可以使用先序遍历+中序遍历,还原树,不过这么写简单。

代码

/**
 * Definition for a binary tree node.
 * 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 "";
        std::string ans = "";
        queue Q;
        Q.push(root);
        while (!Q.empty())
        {
            const auto &index = Q.front();
            ans += to_string(index->val);
            ans += " ";
            if (index->left != NULL)
            {
                ans += std::to_string(index->left->val);
                Q.push(index->left);
            }
            else
                ans += "-1";
            ans += " ";
            if (index->right != NULL)
            {
                ans += std::to_string(index->right->val);
                Q.push(index->right);
            }
            else
                ans += "-1";
            ans += " ";
            Q.pop();
        }
        return ans;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data.empty())
        return NULL;
        //cout << data << endl;
        TreeNode *ans = new TreeNode;
        stringstream s(data);
        map mp;
        int root, left, right;
        while (s >> root >> left >> right)
        {
            if (mp.empty())
            {
                ans->val = root;
                mp[root] = ans;
            }

            if (~left)
            {
                mp[root]->left = new TreeNode(left);
                mp[left] = mp[root]->left;
            }

            if (~right)
            {
                mp[root]->right = new TreeNode(right);
                mp[right] = mp[root]->right;
            }
        }
        return ans;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;

你可能感兴趣的:(算法,数据结构,leetcode)