题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
必须返回char*的接口
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: char* Serialize(TreeNode *root) { if (root == nullptr) return nullptr; string str; queue<TreeNode*> q; // bfs q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { auto node = q.front(); q.pop(); if (node != nullptr) { str += to_string(node->val) + ","; // 加,是为了区分开节点值 q.push(node->left); // 左子树是null也入队 q.push(node->right); } else { str += "#"; } } } auto res = new char[str.length() + 1]; strcpy(res, str.c_str()); res[str.length()] = '\0'; return res; } TreeNode* Deserialize(char *str) { if (str == nullptr) return nullptr; int k = 0; queue<TreeNode*> q; auto root = new TreeNode(getvalue(str, k)); q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { auto node = q.front(); q.pop(); int l = getvalue(str, k); if (l != -1) { auto node_l = new TreeNode(l); node->left = node_l; q.push(node_l); } int r = getvalue(str, k); if (r != -1) { auto node_r = new TreeNode(r); node->right = node_r; q.push(node_r); } } } return root; } int getvalue(char* str, int &k) { int val = 0; while (str[k] != ',' && str[k] != '\0' && str[k] != '#') { val = val * 10 + str[k] - '0'; k++; } if (str[k] == '\0') return -1; if (str[k] == '#') val = -1; k++; return val; } };
leetcode
class Codec { public: // [1,2,3,null,null,4,5] /* res == 2,#,# res == 4,#,# res == 5,#,# res == 3,4,#,#,5,#,# res == 1,2,#,#,3,4,#,#,5,#,# */ string serialize(TreeNode* root) { if (root == nullptr) return "#"; string res = to_string(root->val); res += "," + serialize(root->left); res += "," + serialize(root->right); cout << "res == " << res << endl; return res; } string m_data; int m_index = 0; TreeNode* dfs_rebuild() { if (m_data[m_index] == '#') { m_index += 2; return nullptr; } TreeNode* root = new TreeNode(-1); int sum = 0; int j = m_index; // [0,9]保证了一个节点的值不会被序列化时候的,造成影响 while (j < m_data.size() && m_data[j] >= '0' && m_data[j] <= '9') { sum = sum * 10 + (m_data[j] - '0'); j++; } m_index = j+1; root->val = sum; root->left = dfs_rebuild(); root->right = dfs_rebuild(); return root; } TreeNode* deserialize(string data) { m_data = data; return dfs_rebuild(); } };
2023-剑指-二叉树 文章被收录于专栏
2023-剑指-二叉树