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

设计一个算法来序列化和反序列化二叉搜索树
对序列化/反序列化算法的工作方式没有限制
您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。

1. 非递归先序遍历 + 编码

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string code = "";
        stack<TreeNode*> s;
        while(root||!s.empty()){
            if(root){
                code+=to_string(root->val);
                code.push_back('.');//用于分割所有权值
                s.push(root);
                root = root->left;
            }
            else{
                code.push_back('#');
                code.push_back('.');
                root = s.top(); s.pop();//回到上一层
                root = root->right;//往右走
            }
        }
        return code;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        TreeNode* root = new TreeNode(-1);
        TreeNode* cur = root;
        stack<TreeNode*> s;
        istringstream iss(data);
        string c;
        while (getline(iss, c, '.')){
            if(c.size()==0) continue;//跳过空字符串
            if(c=="#"){
                cur->val = -1;//后面再删除
                if(!s.empty()){
                    cur = s.top(); s.pop();
                    cur->right = new TreeNode(-1);
                    cur = cur->right;//移动到右边
                }
            }
            else{
                s.push(cur);//储存,还要处理右指针
                cur->val = stoi(c);
                cur->left = new TreeNode(-1);
                cur = cur->left;
            }
        }
        return f(root);
    }
    TreeNode* f(TreeNode* root){ //剔除空节点
        if(!root||root->val==-1) return nullptr;
        root->left = f(root->left);
        root->right = f(root->right); 
        return root;
    }
};
posted @ 2023-09-04 13:16  失控D大白兔  阅读(2)  评论(0编辑  收藏  举报