地址 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; } };
有点乱 待优化