acwing 50. 序列化二叉树

地址 https://www.acwing.com/problem/content/46/

请实现两个函数,分别用来序列化和反序列化二叉树。

您需要确保二叉树可以序列化为字符串,并且可以将此字符串反序列化为原始树结构。

样例

你可以序列化如下的二叉树
    8
   / 
  12  2
     / 
    6   4

为:"[8, 12, 2, null, null, 6, 4, null, null, null, null]"

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:


string str;
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
    if (root == NULL) {
        if (!str.empty()) {
            str += ',';
        }
        str += "NULL";
        return str;
    }

    if (!str.empty()) {
        str += ',';
    }
    str += to_string(root->val);

    serialize(root->left);
    serialize(root->right);

    //cout << "str = " << str<<endl;
    return str;
}

string ParseString( string& data, int& val)
{
    string ret;

    if (data[0] == ',') {
        data = data.substr(1);
    }

    if (data.empty()) {
    //    assert(0);
        val = -99999;
        return "";
    }
    else if (data[0] == 'N') {
        val = -99999;
        ret = data.substr(4);
    }
    else if (data[0] >= '0' || data[0] <= '9') {
        int idx = 0;
        while (data[idx] != ',' && idx < data.size()) {
            idx++;
        }
        string numstr = data.substr(0, idx );
        ret = data.substr(idx );
        val = atoi(numstr.c_str());
    }
    else {
        //assert(0);
    }
    if (ret[0] == ',') {
        ret = ret.substr(1);
    }


    return ret;
}
//8,12,NULL,NULL,2,6,NULL,NULL,4,NULL,NULL

TreeNode* deserializeInner(string& data)
{
    if (data.empty() || data == "NULL")
        return NULL;
    
    if (data[0] == ',') {
        data = data.substr(1);
    }
    int val = -99999;
    string nextStr = ParseString(data, val);
    data = nextStr;
    if (val == -99999) {
        return NULL;
    }

    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    memset(root, 0, sizeof(TreeNode));
    root->val = val;


    root->left = deserializeInner(data);
    root->right = deserializeInner(data);

    return root;
}


// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
    if (data.empty() ||data == "NULL")
        return NULL;
    //cout << data<<endl;
    int val = -1;
    string nextStr = ParseString(data, val);

    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    memset(root, 0, sizeof(TreeNode));
    root->val = val;

    root->left = deserializeInner(nextStr);
    root->right = deserializeInner(nextStr);
    return root;
}



};

有点乱 待优化

作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/11358580.html