很难缠的一道题,很多解答都没有按照要求序列化字符串。
- 把二叉树转化为字符串,这步不难,主要是把NULL节点转化为#,并且在所有节点值后面都添加!。
- 用两个vector,分别存储这一次要添加子节点的节点,和下一步要添加子节点的节点。
- 在读取的时候,制定了两个函数,一个函数判断字符串第一个数是不是#,第二个函数读取数字,并把指针移向下一个函数。
- 两个vector轮流一层一层的添加节点,知道最后两个vector都为空。
class Solution { public: char* Serialize(TreeNode* root) { string serial; char* out; if (root == 0) { out = new char[3](); out[0] = '#'; out[1] = '!'; return out; } queue queue_of_node; queue_of_node.push(root); while (!queue_of_node.empty()) { TreeNode* node = queue_of_node.front(); queue_of_node.pop(); if (node == 0) serial = serial + '#' + '!'; else { serial = serial + to_string(node->val) + '!'; queue_of_node.push(node->left); queue_of_node.push(node->right); } } out = new char[serial.size() + 1]; memcpy(out, serial.c_str(), serial.size()); return out; } TreeNode* Deserialize(char* str) { if (str == NULL || str[0] == 0 || str[0] == '#') return 0; vector vector1; vector vector2; int index = 0; TreeNode* root = new TreeNode(readint_of_str(str, index)); vector1.push_back(root); while (!vector1.empty() || !vector2.empty()) { for (auto i : vector1) { addnode(i, "left", str, index, vector2); addnode(i, "right", str, index, vector2); } vector1.clear(); for (auto i : vector2) { addnode(i, "left", str, index, vector1); addnode(i, "right", str, index, vector1); } vector2.clear(); } return root; } void addnode(TreeNode* root, string left_or_right, char* str, int& index, vector& another) { if (str[index] == 0) return; if (getchar_of_str(str, index) == '#') { index = index + 2; return; } else { TreeNode* temp = new TreeNode(readint_of_str(str, index)); if (left_or_right == "left") root->left = temp; else root->right = temp; another.push_back(temp); } } char getchar_of_str(char* str, int& index) { return str[index]; } int readint_of_str(char* str, int& index) { int num = 0; while (str[index] != '!') { num = num * 10 + str[index] - '0'; index++; } index++; return num; } };